多次使用属性时的性能考虑因素

时间:2010-02-08 16:51:33

标签: c# performance optimization properties

我在使用CultureInfo.CurrentCulture

格式化字符串时使用string.format

引用this blog

  

这只是暗示如果   你正在使用CurrentCulture,它   可能值得一读   私有变量而非制作   很多电话   CultureInfo.CurrentCulture,否则   你正在耗尽时钟周期   不必要。

所以根据这位作者

var culture = CultureInfo.CurrentCulture
string.Format(culture,"{0} some format string","some args");
string.Format(culture,"{0} some format string","some other args");

优于

string.Format(CultureInfo.CurrentCulture,"{0} some format string","some args");
string.Format(CultureInfo.CurrentCulture,"{0} some format string","some other args");

根据MSDN,CultureInfo.CurrentCulture is a property

多次访问属性时是否存在性能损失?

我也进行了一些经验分析,我的测试表明,使用局部变量比直接使用属性更昂贵。

Stopwatch watch = new Stopwatch();

            int count = 100000000;
            watch.Start();
            for(int i=0;i<count;i++)
            {
                string.Format(CultureInfo.CurrentCulture, "{0} is my name", "ram");
            }


            watch.Stop();
                 //EDIT:Reset watch
                 watch.Reset();


            Console.WriteLine(watch.Elapsed);
            Console.WriteLine(watch.ElapsedMilliseconds);
            Console.WriteLine(watch.ElapsedTicks);


            Console.WriteLine("--------------------");
            var culture = CultureInfo.CurrentCulture;
            watch.Start();
            for (int i=0; i < count; i++)
            {
                string.Format(culture, "{0} is my name", "ram");
            }


            watch.Stop();

            Console.WriteLine(watch.Elapsed);
            Console.WriteLine(watch.ElapsedMilliseconds);
            Console.WriteLine(watch.ElapsedTicks);

结果:

00:00:29.6116306
29611
68922550970
--------------------
00:00:27.3578116
27357
63676674390

我的测试表明,使用CultureInfo.CurrentCulture属性比使用局部变量更好(这与作者的观点相矛盾)。或者我在这里遗漏了什么?

编辑:我没有在第二次迭代之前重置秒表。因此差异。重置秒表,更新迭代计数并导致此编辑

3 个答案:

答案 0 :(得分:7)

将代码重写为

的一个真正原因
var culture = CultureInfo.CurrentCulture;
String.Format(culture, "{0} some format string", "some args"); 
String.Format(culture, "{0} some format string", "some other args"); 

String.Format(CultureInfo.CurrentCulture, "{0} some format string", "some args");  
String.Format(CultureInfo.CurrentCulture, "{0} some format string", "some other args"); 

是为了便于阅读和维护。现在,如果您出于某种原因需要将文化从CultureInfo.CurrentCulture更改为通过某个配置文件加载的CultureInfo或作为方法传递给参数,您只需将代码更改为一个地点。 性能是这里的次要考虑因素,可能无关紧要,因为这不太可能成为代码中的瓶颈。

答案 1 :(得分:3)

如果分析器将其显示为代码中的重要问题,并且放入局部变量使其更快,则只应将CultureInfo.CurrentCulture优化为局部变量。此配置文件显示两者都不是真的所以我不会把它放到本地。

答案 2 :(得分:2)

您的代码中存在错误。在您的测试代码中,您不会重置秒表。重置秒表时,您会发现使用缓存的参考实际上更快。 CultureInfo.CurrentCulture并不便宜,但string.Format要贵得多。