Difference between declaring variables before or in loop?

前端 未结 25 2075
长发绾君心
长发绾君心 2020-11-22 02:37

I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference? A (q

25条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 03:07

    It depends on the language and the exact use. For instance, in C# 1 it made no difference. In C# 2, if the local variable is captured by an anonymous method (or lambda expression in C# 3) it can make a very signficant difference.

    Example:

    using System;
    using System.Collections.Generic;
    
    class Test
    {
        static void Main()
        {
            List actions = new List();
    
            int outer;
            for (int i=0; i < 10; i++)
            {
                outer = i;
                int inner = i;
                actions.Add(() => Console.WriteLine("Inner={0}, Outer={1}", inner, outer));
            }
    
            foreach (Action action in actions)
            {
                action();
            }
        }
    }
    

    Output:

    Inner=0, Outer=9
    Inner=1, Outer=9
    Inner=2, Outer=9
    Inner=3, Outer=9
    Inner=4, Outer=9
    Inner=5, Outer=9
    Inner=6, Outer=9
    Inner=7, Outer=9
    Inner=8, Outer=9
    Inner=9, Outer=9
    

    The difference is that all of the actions capture the same outer variable, but each has its own separate inner variable.

提交回复
热议问题