Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"GLOBAL could be very inefficient"

I am using (in Matlab) a global statement inside an if command, so that I import the global variable into the local namespace only if it is really needed.

The code analyzer warns me that "global could be very inefficient unless it is a top-level statement in its function". Thinking about possible internal implementation, I find this restriction very strange and unusual. I am thinking about two possibilities:

  1. What this warning really means is "global is very inefficient of its own, so don't use it in a loop". In particular, using it inside an if, like I'm doing, is perfectly safe, and the warning is issued wrongly (and poorly worded)

  2. The warning is correct; Matlab uses some really unusual variable loading mechanism in the background, so it is really much slower to import global variables inside an if statement. In this case, I'd like to have a hint or a pointer to how this stuff really works, because I am interested and it seems to be important if I want to write efficient code in future.

Which one of these two explanations is correct? (or maybe neither is?)

Thanks in advance.

EDIT: to make it clearer: I know that global is slow (and apparently I can't avoid using it, as it is a design decision of an old library I am using); what I am asking is why the Matlab code analyzer complains about

if(foo==bar)
    GLOBAL baz
    baz=1;
else
    do_other_stuff;
end

but not about

GLOBAL baz
if(foo==bar)
    baz=1;
else
    do_other_stuff;
end

I find it difficult to imagine a reason why the first should be slower than the second.

like image 252
Federico Poloni Avatar asked Oct 25 '11 11:10

Federico Poloni


1 Answers

To supplement eykanals post, this technical note gives an explanation to why global is slow.

... when a function call involves global variables, performance is even more inhibited. This is because to look for global variables, MATLAB has to expand its search space to the outside of the current workspace. Furthermore, the reason a function call involving global variables appears a lot slower than the others is that MATLAB Accelerator does not optimize such a function call.

like image 62
Ghaul Avatar answered Oct 13 '22 12:10

Ghaul