-1

我是 C# 的初学者,正在尝试了解在不同范围内声明变量的效果。两者之间是否存在明显的性能差异:

示例 1

class A
{
   static int i;
   static string temp;
}

class B
{
   while(true)
   {
       A.i=10;
       A.temp="Hello";
   }
}

示例 2

class B
{
   int i;
   string temp;
   while(true)
   {
       i=10;
       temp="Hello";
   }
}

示例 3

class A
{
   public int i;
   public string temp;
}

class B
{
A D = new A();
   while(true)
   {
       D.i=10;
       D.temp="Hello";
   }
}
4

1 回答 1

3

The first code snippet shares both variables: they get allocated statically, and all threads would use them in concurrent environments. This is very bad - one should avoid situations like that in production code.

The second and the third code snippets are thread safe. The third snippet groups variables i and temp; the second snippet does not. In addition, the third snippet needs an extra allocation of an object, and creates an object to be collected upon return (of course it never returns because of the infinite while (true) loop, so it does not really matter).

If the two variables do not belong together logically, you should avoid making a class for them. If they do belong together, you should move the code that uses these variables into the class that declares them.

As far as the performance and memory implications go, the third snippet requires an extra chunk of memory compared to the second one, but it is too small to pay attention to. The performance difference will be nearly impossible to detect, so you should not worry about it much: in most cases, it is best to optimize your code for readability.

于 2013-07-08T01:04:01.290 回答