GLOBAL could be very inefficient

8 views (last 30 days)
I am using 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.
Thanks in advance.
  1 Comment
Federico
Federico on 26 Oct 2011
This is cross-posted to http://stackoverflow.com/questions/7888899/global-could-be-very-inefficient. Sorry about that, but I got a 404 when posting here, so I assumed it hadn't worked.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 26 Oct 2011
I would think that each time "global" is encountered, it needs to go through all the names in the argument list, and test to see if each already exists in the current namespace and whether it is already marked as "global" there. If it does exist in the namespace and is not global, it needs to give a warning about the conflict (I do not recall how conflict is resolved).
If it does not exist in the namespace then it needs to check the global namespace and if it exists there then it creates the variable in the local namespace and mark it as global and associate it with the existing value; if it does not exist in the global namespace it needs to create it there and initialize it to [] and then import it to the local namespace and mark it as global and associate it with the (newly created) existing value.
This is not necessarily more work if not done in a top-level command, but people would tend to put the construct in a loop, or in multiple non-exclusive places in conditional structures. It is a lot easier for a person writing mlint warnings to not have to add clarifications like, "Unless you can prove those "global" will only be executed once, in which case it isn't less efficient but it is still bad form"

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!