In a compiled language, all you do is premature optimization . I assume that the interpreted language may save a little, but even there it seems that your gain will be so minimal that (in my experience) an unusual way to code a for loop.
To answer your question directly in C #, no, the compiler doesnโt optimize anything by caching. I could easily create a new array with a new length during the loop. That way, it will load the length of the array every time it evaluates a stop condition. Or, even worse, I can't use the โtraditionalโ style stopping conditions and maybe you will need to evaluate the function you need to know to stop.
However, here is a simple program:
static void Main( string[] args ) { int[] integers = new int[] { 1, 2, 3, 4, 5 }; for( int i = 0; i < integers.Length; i++ ) { Console.WriteLine( i ); } }
And here is IL (with nops removed):
IL_000d: call void [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle) IL_0012: stloc.0 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: br.s IL_0024 IL_0018: ldloc.1 IL_0019: call void [mscorlib]System.Console::WriteLine(int32) IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: add IL_0023: stloc.1 IL_0024: ldloc.1 IL_0025: ldloc.0 IL_0026: ldlen IL_0027: conv.i4 IL_0028: clt IL_002a: stloc.2 IL_002b: ldloc.2 IL_002c: brtrue.s IL_0017
The key answer to your question here is that it pushes the array to location 0 on the stack, then at run time IL_0026 to call the length of the array, IL_0028 does less than the comparison, and finally going to IL_0017 if the estimate is correct.
By caching the length of the array, all you save is a call to ldlen and stloc. The ldlen statement should be quick, since getting the length of the array is not too long.
EDIT:
The main difference from the list is as follows:
IL_002b: callvirt instance int32 class [mscorlib]System.Collections.Generic.List`1<int32>::get_Count()
callvirt will take longer, but this whole function realistically returns a private variable.
You would be better off worrying about things that take milliseconds - for example, database calls or optimizing SQL queries so that they are faster, etc., than trying to shave off individual IL operations.