title: Does visual studio automatically optimize for loops in C#?
body: <p>When accessing an array of objects, I think it is clear to define a variable like 'obj' in the for loops, as follows:</p>
  <pre><code>var objects = new object[10000];
  
  //......assign values to objects
  
  
  //When visiting objects, I think it is clear to define a variable 'obj' in the for loops
  for (int i = 0; i &lt; objects.Length; i++)
  {
      var obj = objects[i];
  
      //......visit obj which will be used for many times, so define the obj to simplify the codes
  
  }
  </code></pre>
  <p>But I am concerned with its efficiency. I worry that repeated 'obj' will be created.</p>
  <p>Should I define the variable in front of the for loops as follow? As well as defining a variable for objects.Length.</p>
  <pre><code>int len = objects.Length;
  object obj2;
  for (int i = 0; i &lt; len; i++)
  {
      obj2 = objects[i];
  
      //visit obj
      //......
  }
  </code></pre>
  <p>Or compiler in Visual Studio will optimize for it?</p>