9

可能重复:
在循环内部还是外部声明变量更好?

Resharper 希望我改变这一点:

int Platypus;
string duckBill1;
string duckBill2;
string duckBill3;
. . .
using (OracleDataReader odr = ocmd.ExecuteReader()) {
    while (odr.Read()) {
        Platypus = odr.GetInt32("Platypus");
        duckBill1 = odr.GetString("duckBill1");
        duckBill2 = odr.GetString("duckBill2");
        duckBill3 = odr.GetString("duckBill3");
        switch (Platypus) {
        . . .

...对此:

using (OracleDataReader odr = ocmd.ExecuteReader()) {
    while (odr.Read()) {
        int Platypus = odr.GetInt32("Platypus");
        string duckBill1 = odr.GetString("duckBill1");
        string duckBill2 = odr.GetString("duckBill2");
        string duckBill3 = odr.GetString("duckBill3");
        switch (Platypus) {
        . . .

...但是以这种方式(至少看起来),变量被声明 N 次,每次通过 while 循环一次。Resharperized 方式真的比原来的更好吗?

4

4 回答 4

17

是的,这更好,因为您限制了声明变量的范围。在循环内声明它们不会对性能产生影响。Resharper 建议进行此更改的原因是您没有在循环之外使用它们。

于 2012-08-16T16:45:47.177 回答
9

一般来说,在尽可能窄的范围内声明变量是一种很好的编程习惯。原因是:

  1. 信息隐藏。
  2. 更容易理解。
  3. 不太可能把事情搞砸。

尽管看起来变量似乎是在循环中的每次迭代中新声明的,但它们是在编译时声明的,而不是在运行时声明的。在堆栈帧上为变量 [s] 分配空间,并且在循环中的每次迭代中重复使用相同的空间。

于 2012-08-16T16:52:22.747 回答
4

Yes, but declaring them doesn't take any time at runtime. They don't take up any more memory becaues the compiler will just reuse their memory locations.

于 2012-08-16T16:49:58.397 回答
2

The compiler will generally optimize such expressions and "lift" the variable declaration outside of the loop, since the variable itself is not dependent on the loop conditions. This effectively produces the code you demonstrated in the first example.

In this case, Resharper's suggestion is just to remove some redundant lines of code, in addition to reducing their pre-compiled scope.

于 2012-08-16T16:48:37.880 回答