Optimizing your for-loop

I use for-loops on a daily basis. I use them when I write Javascript and in C#. The for-loop is very common and easy to use. Here is a typical example of a for-loop in C#:

for (int i = 0; i < arr.Length; i++)
{
     object arrayItem = arr[i];
     //do something with arrayItem
}

Even though this is a perfectly legal example of a for-loop there is room for improvement.
Each iteration of the for-loop the Length property of the array will be retrieved. The performance penalty on this is minimal but when your array consists of thousands of objects the performance penalty can be noticeable. The answer is:  ‘caching’.

The for-loop can be changed to cache the Length-value in a variable and then use that variable instead of the length property. Example:

for (int i = 0, len = arr.Length; i < len; i++)
{
     object arrayItem = arr[i];
     //do something with arrayItem
}

Caching the value of the Length-property is always a good thing to do even if you expect your array yo be minimal in length. There is no penalty for doing this on small arrays, only a benefit when used on large arrays. Therefore I recommend to always use caching in your array.

It works in C# as well as in Javascript and probably on a lot of more languages.

Happy coding.

  1. Thanks for this information and useful in case of extremely large arrays. In normal LOB applications the arrays will be much shorter.
    I think you should keep the end user happy (with a reasonable performant app) but focus on the developer maintaining your app. He will be thankful if he can read your source code without being distracted by performance optimizing ‘code noise’.

    Compare the following (C#):

    foreach (object arrayItem in arr)
    {
    //do something with arrayItem
    }

    with:

    for (int i = 0, len = arr.Length; i < len; i++)
    {
    object arrayItem = arr[i];
    //do something with arrayItem
    }

    As a developer I understand the first construct at first sight but for the second I have to look a couple of seconds what is happening between the brackets.

    In case the array is huge and the performance improvement is measurable, switch to your construct and add a comment above the for-loop telling the reader that you chose this construct on purpose.

    Keep on sharing!

    • Mike H
    • April 2nd, 2010

    Are you sure this will compile? You didn’t set “len” to a type. Wouldn’t you need:

    for (int i = 0, int len = arr.Length; i < len; i++)
    2 {
    3 object arrayItem = arr[i];
    4 //do something with arrayItem
    5 }

    but can't you just do:
    int len = arr.Length;
    for (int i = 0, i < len; i++)
    2 {
    3 object arrayItem = arr[i];
    4 //do something with arrayItem
    5 }

    • Mike
    • April 3rd, 2010

    Nevermind, I see now there was a comma after the 0 so both were ints…
    for (int i = 0, int len = arr.Length; i < len; i++)

    This still seems more readable though:
    int len = arr.Length;
    for (int i = 0, i < len; i++)

    • Happy to see that you have noticed that the initialization of both integers can happen on the same line like I did.

      About the comment you make about defining ‘len’ outside the ‘for loop’. If you define it that way the variable is created outside the scope of your ‘for loop’ and will be available outside the loop. In most cases the ‘len’ variable is only needed in the loop and should not be defined outside the loop.

    • StephenWInburn
    • July 16th, 2014

    My question is this: Is it particular to the for loop that it will now only call Length once at variable instantiation, or does it call it on each pass? It seems the former must be true, else there would be no gain.

      • StephenWInburn
      • July 16th, 2014

      Nevermind, I figured out my noob question’s answer.

      • Hi Stephen,

        First of all, there are no stupid questions. But you are right. The value of the .Length property is assigned to the len variable and from thereafter the .Length property isn’t used anymore, ‘i’ is compared against ‘len’. The benefits are significantly in JavaScript on older browsers or IE.

        The benefits on C# are only worth mentioning if you compile in debug mode because in release mode the compiler does the optimizing for you. The effects are neglectable. That being said, this optimizing is best for non compiled languages.

  2. Hi! In last framework versions this optimization will not give you performance increase, because of compiler optimizations. Look at core code to see difference. Length value is cached by default.

  1. No trackbacks yet.