title: "GLOBAL could be very inefficient"
body: <p>I am using (in Matlab) a <code>global</code> statement inside an if command, so that I import the global variable into the local namespace only if it is really needed.</p>
  
  <p>The code analyzer warns me that "<code>global</code> 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:</p>
  
  <ol>
  <li><p>What this warning really means is "<code>global</code> 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)</p></li>
  <li><p>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.</p></li>
  </ol>
  
  <p>Which one of these two explanations is correct? (or maybe neither is?)</p>
  
  <p>Thanks in advance.</p>
  
  <p>EDIT: to make it clearer: I know that <code>global</code> 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</p>
  
  <pre><code>if(foo==bar)
      GLOBAL baz
      baz=1;
  else
      do_other_stuff;
  end
  </code></pre>
  
  <p>but not about </p>
  
  <pre><code>GLOBAL baz
  if(foo==bar)
      baz=1;
  else
      do_other_stuff;
  end
  </code></pre>
  
  <p>I find it difficult to imagine a reason why the first should be slower than the second.</p>