global variables are fast? Functions make copies or not?

26 次查看(过去 30 天)
In the description, I read: "if several functions all declare a particular variable name as global, then they all share a single copy of that variable." This means that every funcion copy that variable and slow down the code? Or global variables can be used immidiatelly, and the copy is virtual?
  5 个评论
Adam
Adam 2017-7-18
Well if you want runtime then don't use global variables. They are slow. Period.
David Smith
David Smith 2020-6-15
Somewhere in the 2010 time frame, I wrote my own versions of some common sorting algorithms using recursion, of course passing fragments of vectors into and out of function calls. At that time, the performance was shockingly slow - for large amounts of data, quick sort, for example, was O(N sq). I was able to use global variables to improve that speed significantly. Then, some time later, I ran it again and the performance was O(N log N) as expected. After much inquiring, I discuvered that the Matlab function calling process had been optimized so that it did not pass a copy of an array into a function unless the function changed the data. That made passing arrays quicker than the global implementation.

请先登录,再进行评论。

回答(2 个)

Stephen23
Stephen23 2017-7-18
编辑:Stephen23 2017-7-18
These will be faster than globals and let you access the same data over multiple function calls:
  1. persistent.
  2. nested functions.

Jan
Jan 2017-7-18
编辑:Jan 2017-7-18
There are many discussions about the performance of global variables in the net. Simply search in thuis forum or using an internet search engine.
Passing variables as input is faster than sharing them as globals from the viewpoint of the run-time. But if you take into account the time for maintaining and debugging the code, globals are an absolute DON'T. While code with some 1000s lines of code might work with globals, expaning the code or letting it run together with arbitrary other tools will lead to unsolvable problems. You cannot control, where the last changes has been made and cannot prevent other codes to use the same names for global variables as you do. Therefore it is recomended frequently, not to use globals at all.
By the way: Asking the forum is always a good idea. And you can simply check this by your own also. Write some code and implement the shared variable as input argument or as global. Then use timeit or tic/for k = 1:1000, yourCode; end, toc to measure the runtime.

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by