global variables are fast? Functions make copies or not?
23 views (last 30 days)
Show older comments
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 Comments
Adam
on 18 Jul 2017
Well if you want runtime then don't use global variables. They are slow. Period.
David Smith
on 15 Jun 2020
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.
Answers (2)
Jan
on 18 Jul 2017
Edited: Jan
on 18 Jul 2017
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.
0 Comments
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!