Why makes storing a reference instead of requesting it twice my application so much slower?
<p>An object <code>memory</code> has a method with the signature</p>

<pre><code>BinaryPattern const&amp; getPattern(unsigned int index) const;
</code></pre>

<p>I'm using this in the following for-loop:</p>

<pre><code>for (unsigned int k = 0; k &lt; memory-&gt;size(); k++) {
    const BinaryPattern s = memory-&gt;getPattern(k);
    w += s.at(i) * s.at(j);
}
</code></pre>

<p>This is very slow. Surprisingly, I found that the following is much faster:</p>

<pre><code>for (unsigned int k = 0; k &lt; memory-&gt;size(); k++) {
    w += memory-&gt;getPattern(k).at(i) * memory-&gt;getPattern(k).at(j);
}
</code></pre>

<p>"getPattern()" does not do any computations, it pretty much just returns the pattern that is stored in a vector.</p>

<p>Why is it so much slower when I store the reference in a variable? I initially did this to speed things up, as I expected retrieving the reference twice to be slower.</p>
