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 个评论
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 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!