何时在 C# 中声明关于 efficiency/speed 的变量

When to declare variables in C# regarding efficiency/speed

我正在 运行 实施某事,完全是为了提高效率而构建的。我在这个话题上还没有那么丰富的经验,想知道什么时候声明变量最好。我的代码的以下部分特别是:

//Variables not declared in the next part are declared here (like xx, y1, x1.....)
    for(s = 0; s < this.Width; s++)
        {
            y = ymin;
            for(z = 0; z < this.Height; z++)
            {
                x1 = 0;
                y1 = 0;
                looper = 0;
                while(looper < curMaxIter && Math.Sqrt((x1 * x1) + (y1 * y1)) < 2)
                {
                    looper++;
                    xx = (x1 * x1) - (y1 * y1) + x;
                    y1 = 2 * x1 * y1 + y;
                    x1 = xx;
                }
                double perc = looper / (double)curMaxIter;
                int val = ((int)(perc * 255));
                b.SetPixel(s,z,cs[val]);
                y += intigralY;
            }
            x += intigralX;
        }

正如你们想象的那样,这个while循环持续了一段时间......我想通过任何方式尽可能减少它所花费的时间,而结果是一样的。这整个代码部分再次 运行 每帧数千次(我正在为那些好奇的人渲染 Mandelbrot 图像)。 我的主要问题:在我使用变量之前声明变量(如 perc 和 val,但也像 xx、y1 和 x1)是否更快? (如 perc 和 val)或更好地在整个循环之前声明它们? (就像我对 xx、y1 和 x1 等所做的那样)

我推荐阅读Compilers - What Every Programmer Should Know About Compiler Optimization。因此,您尝试进行的微优化很可能 的效果为零。编译器和 JIT 团队非常聪明。例如:

What’s the difference between RyuJIT and Visual C++ in terms of optimization capabilities? Because it does its work at run time, RyuJIT can perform optimizations that Visual C++ can’t. For example, at run time, RyuJIT might be able to determine that the condition of an if statement is never true in this particular run of the application and, therefore, it can be optimized away.

Performance example, which one is faster?:

List<User> list = new List<User>();
User u;

foreach (string s in l)
{
    u = new User();
    u.Name = s;
    list.Add(u);
}

或者这个:

List<User> list = new List<User>();

foreach (string s in l)
{
    User u = new User();
    u.Name = s;
    list.Add(u);
}

答案:

Performance-wise both examples are compiled to the same IL, so there's no difference.

所以唯一的判断方法是 运行 测试本身......也就是说,如果你 绝对 需要那个速度。

其他好文章:

The Sad Tragedy of Micro-Optimization Theater

Hardware is Cheap, Programmers are Expensive

您可以使用 Visual Studio 性能分析器 https://msdn.microsoft.com/en-us/library/ms182372.aspx