我要声明的变量尽可能接近的范围,在那里他们将被使用? [英] Should I declare variables as close as possible to the scope where they will be used?

查看:294
本文介绍了我要声明的变量尽可能接近的范围,在那里他们将被使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ReSharper的的通常表示我,我还在寻找一个很好的理由,为什么这样做。

ReSharper usually suggests me that, and I'm still looking for a good reason of why to do that.

的唯一一件事那来到我想到的是,声明更接近它会被使用的范围,可避免在某些情况下,没有必要对其进行初始化(因为一个条件,等等。)

The only thing that came to my mind is that declaring it closer to the scope it will be used, can avoid initializing it in some cases where it isn't necessary (because a condition, etc.)

与相关的东西如下:

int temp;
foreach (var x in collection) { 
    temp = x.GetValue();
    //Do something with temp
}

是比<真的不一样的东西/ p>

Is that really different than

foreach (var x in collection) {
    int temp = x.GetValue();
    //...
}



我的意思是,是不是第二个代码更昂贵,因为它是分配内存每次?或者都是一样的吗?当然,完成后在循环,在第二个代码中的垃圾收集器将需要约温度变量照顾,但不是在第一个...

I mean, isn't the second code more expensive because it is allocating memory everytime? Or are both the same? Of course, after finished the loop, in the second code the garbage collector will take care about temp variable, but not in the first one...

推荐答案

第二实施例的成本是微不足道的。唯一的区别是,在第一个例子中,温度将可在循环的范围之内,因而会存在比,如果你宣布它在循环中更长的时间。

The cost of the second example is negligible. The only difference is that in the first example, temp will be available outside the scope of the for loop, and thus it will exist longer than if you declared it inside the for loop.

如果你不这样做的需要温度之外循环,它不应该是循环外部声明。像其他人所说,可读性和风格更在这里打球比的性能和内存。

If you don't need temp outside the for loop, it shouldn't be declared outside that loop. Like others have said, readability and style are more at play here than performance and memory.

这篇关于我要声明的变量尽可能接近的范围,在那里他们将被使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆