title: Performance of swapping two elements in MATLAB
body: <p>Purely as an experiment, I'm writing sort functions in MATLAB then running these through the MATLAB profiler. The aspect I find most perplexing is to do with swapping elements.</p>
  
  <p>I've found that the "official" way of swapping two elements in a matrix</p>
  
  <pre><code>self.Data([i1, i2]) = self.Data([i2, i1])
  </code></pre>
  
  <p>runs much slower than doing it in four lines of code:</p>
  
  <pre><code>e1 = self.Data(i1);
  e2 = self.Data(i2);
  self.Data(i1) = e2;
  self.Data(i2) = e1;
  </code></pre>
  
  <p>The total length of time taken up by the second example is <strong>12 times</strong> less than the single line of code in the first example.</p>
  
  <p>Would somebody have an explanation as to why?</p>