global variables are fast? Functions make copies or not?

24 views (last 30 days)
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
Adam on 18 Jul 2017
Well if you want runtime then don't use global variables. They are slow. Period.
David Smith
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.

Sign in to comment.

Answers (2)

Stephen23
Stephen23 on 18 Jul 2017
Edited: Stephen23 on 18 Jul 2017
These will be faster than globals and let you access the same data over multiple function calls:
  1. persistent.
  2. nested functions.

Jan
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.

Community Treasure Hunt

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

Start Hunting!