title: Caching variables in a `for` loop
body: <p>I've been reading tips about Javascript performance boosting and one tip said to cache all the variables (that don't change) in the loops comparer statement and I was wondering if this also applied to .NET.</p>
  
  <p>Assuming I had a simple for loop, which one of the following would be faster or would they be the same?</p>
  
  <p>No Cache:</p>
  
  <pre><code>for (int i = 0; i &lt; someArray.Length; i++)
  {
  
  }
  </code></pre>
  
  <p>With Cache:</p>
  
  <pre><code>for (int i = 0, count = someArray.Length; i &lt; count; i++)
  {
  
  }
  </code></pre>
  
  <p>According to the article "caching" the value of <code>Length</code> cuts out one operation in the loop because its faster to access local variables compared to accessing members of an object.
  Is it actually faster declaring a local variable compared to simply accessing the member? Does the compiler pick up on this and automatically cache the value? Is there any negatives in declaring a local variable over accessing the member?</p>
  
  <p>Whilst speed is probably a key factor here, its not the only one. My next question would probably be which one is more efficient. Which uses less memory allocations? Which performs less stack manipulation? etc...</p>
  
  <p>From comments, it seems accessing <strong>array</strong> lengths is pretty fast. Lets say I use an <code>IList&lt;&gt;</code> instead. Would caching the value of <code>Count</code> be faster than retrieving it each iteration?</p>