Using Globals instead of passing large arrays in Matlab

隐身守侯 提交于 2019-12-01 20:52:38

@mutzmatron answered my question in a comment, so this is a repost:

Actually Matlab passes by reference, unless it decides it needs to pass by value...see the explanation here: http://www.mathworks.com/matlabcentral/answers/...

I have also read everywhere that global's are generally a bad idea as well. And, specifically, I disagree. Each tool has its own purpose.

I've been working on optimizing code and have found, of all the "better options" presented, using global's in my application speeds up execution of the code by a full 20%!

The code is for processing GPS signals ... there are a number of parameters that are commonly used by all functions that define certain characteristics of a GPS signal. Also, there are numerous nested functions and iterative calls to those functions.

It might be the case that passing a single parameter to a function is somewhat faster than that function accessing a global variable. In my case, it is much faster for each function to access the 3 or 4 global variables that it needs than to pass all 10 parameters all the way up the chain of nested functions.

A tic-toc of 8.5 seconds using global variables is faster than 10.5 seconds using parameter passing or nested functions. So, bad idea? I'll take performance, thanks.

My point? Use globals if globals work better. Try it either way ... but the moment you change the large array in a function, that array now gets copied locally instead of just being referenced. I'd rather look-up a global then make a 70MB copy.

In lower-level languages, I would agree to avoid global variables the best you can ... but those languages offer pointers and constants. MATLAB just isn't made for people who actually know how to program and how to optimize. If the interpreter doesn't optimize for you; it just seems you're SOL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!