can Matlab global variables yield better performance in Matlab?

半腔热情 提交于 2019-12-20 05:19:05

问题


I hate using global variables, and everyone should. If a language has no way around using global variables it should be updated. Currently, I don't know any good alternative to using global variables in Matlab, when efficiency is the goal.

Sharing data between callbacks can be done in only 4 ways that I am aware of:

  1. nested functions
  2. getappdata (what guidata uses)
  3. handle-derived class objects
  4. global variables

nested functions forces the entire project to be in a single m-file, and handle-derived class objects (sent to callbacks), gives unreasonable overhead last I checked.

Comparing getappdata/guidata with global variables, in a given callback you can write(assuming uglyGlobal exists as a 1000x1000 mat):

global uglyGlobal;
prettyLocal = uglyGlobal;
prettyLocal(10:100,10:100) = 0;
uglyGlobal = prettyLocal;

or you can write (assuming uglyAppdata exists as a 1000x1000 mat):

prettyLocal = getappdata(0,'uglyAppdata');
prettyLocal(10:100,10:100) = 0;
setappdata(0,'x',prettyLocal);

The above snippets should work in the same way. It could be (but is not guaranteed) more efficient with just:

global uglyGlobal;
uglyGlobal(10:100,10:100) = 0;

This snippet, unlike the previous ones, may not trigger a copy-on-write in Matlab. The data in the global workspace is modified, and (potentially) only there.

however, if we do the innocent modification:

global uglyGlobal;
prettyLocal = uglyGlobal;
uglyGlobal(10:100,10:100) = 0;

Matlab will ensure that prettyLocal gets its own copy of the data. The third line above will show up as the culprit when you profile. To make that worse on my brain(globals tend to do that), any other workspace that exists that has a local reference to the global, will make a copy-on-write trigger for that variable, one for each.

However, iff one makes sure no local references exists:

Is it true that global variables, used carefully can yield the best performance programs in Matlab?

Note: I would provide som timing results, but unfortunately I no longer have access to Matlab.

来源:https://stackoverflow.com/questions/41910237/can-matlab-global-variables-yield-better-performance-in-matlab

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