MATLAB: Does declaring a global variable take so much time

globalprofilerspeed up

I have a function in from a larger program that I profiled in order to try and find some places to gain some speed. The global declaration in the function below takes up by far the most time. Can anyone tell me why this would take so much time and suggest possible solutions? Unfortunately, giving it as an argument to the function is not an option.

Best Answer

Just a quick test:
num = 100000000;
a = 1;
for ii = 1:num;
a = ii;
global b;
b = 1;
for ii = 1:num;
b = ii;
The problem with allocating globals is that ALL programs that are running must be made aware: "Look here, I'm a global and I demand your attention", so that's an overhead. All the normal tricks that a program could do to optimize the use of normal arrays go out the window when you make them globals. Also, and maybe this is not applicable here, good luck making your program thread safe. The solution:
  1. Don't use globals, but you don't want to hear that
  2. Pass them explicitly, something else you don't want to hear.
  3. Don't modify them so often.