title: Unexpected slowdown of function that modifies array in-place
body: <p>This bug is due to Matlab being too smart for its own good.</p>
  
  <p>I have something like </p>
  
  <pre><code>for k=1:N
      stats = subfun(E,k,stats);
  end
  </code></pre>
  
  <p>where <code>stats</code>is a <code>1xN</code>array, <code>N=5000</code> say, and <code>subfun</code> calculates <code>stats(k)</code>from <code>E</code>, and fills it into stats</p>
  
  <pre><code>function stats = subfun(E,k,stats)
      s = mean(E);
      stats(k) = s;
  end
  </code></pre>
  
  <p>Of course, there is some overhead in passing a large array back and forth, only to fill in one of its elements. In my case, however, the overhead is negligable, and I prefer this code instead of </p>
  
  <pre><code>for k=1:N
      s = subfun(E,k);
      stats(k) = s;
  end
  </code></pre>
  
  <p>My preference is because I actually have a lot more assignments than just <code>stats</code>.
  Also some of the assignments are actually a good deal more complicated.</p>
  
  <p>As mentioned, the overhead is negligable. But, if I do something trivial, like this inconsequential if-statement</p>
  
  <pre><code>for k=1:N
      i = k;
      if i&gt;=1
          stats = subfun(E,i,stats);
      end
  end
  </code></pre>
  
  <p>the assignments that take place inside subfun then suddenly takes "forever" (it increases much faster than linearly with N). And it's the assignment, not the calculation that takes forever. In fact, it is even worse than the following nonsensical <code>subfun</code></p>
  
  <pre><code>function stats = subfun(E,k,stats)
      s = calculation_on_E(E);
      clear stats
      stats(k) = s;
  end
  </code></pre>
  
  <p>which requires re-allocation of stats every time.</p>
  
  <p>Does anybody have the faintest idea why this happens?</p>