1

Visual Studio 或 monodevelop 中的 C# 编译器是否会针对内存优化变量声明?

例如,在示例 1 中,C# 是否在每次 for 循环迭代中创建一个新的 4 字节内存?在示例 2 中,每个函数调用一个新的 4 字节内存?示例 3,每个类一个新的 4 字节内存?

C# 是否将所有 3 个示例优化为仅将一个 int 用于内存目的?

三个例子: 1:for循环内的第一个:

void testfunction(){
   for(int j=0;j<100000;j++){
      int x = j*2;
      //x used for a lot of stuff
   }
}

2:在for循环之外:

void testfunction(){
   int x=0;
   for(int j=0;j<100000;j++){
      x = j*2;
      //x used for a lot of stuff
   }
}

3:函数外和for循环:

int x=0;
void testfunction(){
   for(int j=0;j<100000;j++){
      x=j*2;
      //x used for a lot of stuff
   }
}
4

1 回答 1

2

我不知道关于 C# 的细节,但 C 的规则仍然适用,我将在下面解释。

方法一

void testfunction(){
   for(int j=0;j<100000;j++){
      int x = j*2;
      //x used for a lot of stuff
   }
}

The stack reference to x is reassigned every iteration. This is an extremely fast operation and you would probably never have any appreciable slowdown because of this.

Method 2

void testfunction(){
   int x=0;
   for(int j=0;j<100000;j++){
      x = j*2;
      //x used for a lot of stuff
   }
}

This is the most correct and fastest method. The x stack reference is only assigned once and is used throughout the duration of the function.

Method 3

int x=0;
void testfunction(){
   for(int j=0;j<100000;j++){
      x=j*2;
      //x used for a lot of stuff
   }
}

This method is not thread-safe if testfunction is public, as two threads could be running testfunction at the same time and thrasing the values of x for each other. Do not do this, as there is no speed, memory or readability gain.

于 2013-08-21T01:08:11.180 回答