Should array length be stored into a local variable in C#?
I&#x27;m not a C# developer, but this kind of thing seems to permeate almost all languages in one form or another.<p>Maybe it is just a style and readability thing; or maybe (as suggested elsewhere as well) it is meant to be reused elsewhere in the system, so it is cached in a variable for later use.<p>Or, it&#x27;s possible that at one time - maybe early in the early days of .NET - doing it this way was more optimized, and the habit stuck with developers (perhaps they all read the same article in the knowledge base about it?). If that&#x27;s the case, it&#x27;s a bit of &quot;premature optimization&quot;, but one that doesn&#x27;t apparently harm anything.<p>What I do wonder is if certain other changes could change the speed?<p>At least it might be interesting to see in these trivial cases; I admit that in more complex loops it might not be advisable.<p>But - for instance, what if rather than iterating thru the array from the 0th element to the length of the array, you instead started from the last element and iterated backwards, until you hit zero? That way, you wouldn&#x27;t be checking the length of the array, but rather for zero?<p>The code for such a test might look like:<p><pre><code>    public int WithoutVariable() {
        int sum = 0;
        for (int i = array.Length - 1; i &gt; -1; i--) {
            sum += array[i];
        }
        return sum;
    }
</code></pre>
I&#x27;m not sure that a &quot;with variable&quot; version would make much difference (or sense), but here it is for completeness sake:<p><pre><code>    public int WithVariable() {
        int sum = 0;
        int length = array.Length - 1;
        for (int i = length; i &gt; -1; i--) {
            sum += array[i];
        }
        return sum;
    }
</code></pre>
Again - I&#x27;m not a C# developer - maybe my code is wrong above, but hopefully it gets the idea across.<p>Would this work better? Would it be faster? What would the JIT compiler create? Maybe it wouldn&#x27;t be any faster or better than the ForEach examples?<p>I honestly don&#x27;t know - but if anybody wants to give it a shot, I&#x27;d be curious as to the results...<p>EDIT: I noticed that I said &quot;checking for zero&quot; - but I modified my code to check for -1 as the boundary; I suppose the check in the loops could be modified to be &quot;i == 0;&quot; instead. I&#x27;m not sure if whether doing an &quot;i &gt;= 0;&quot; vs &quot;i == 0;&quot; vs &quot;i &gt; -1;&quot; which is faster - another thing to check, I suppose...