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

ram*_*ram 5 c# optimization performance properties

我在使用CultureInfo.CurrentCulture时形成我的字符串时使用string.format

引用此博客

这只是暗示如果您经常使用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");
Run Code Online (Sandbox Code Playgroud)

比...更好

string.Format(CultureInfo.CurrentCulture,"{0} some format string","some args");
string.Format(CultureInfo.CurrentCulture,"{0} some format string","some other args");
Run Code Online (Sandbox Code Playgroud)

根据MSDN,CultureInfo.CurrentCulture是一个属性

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

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

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);
Run Code Online (Sandbox Code Playgroud)

结果:

00:00:29.6116306
29611
68922550970
--------------------
00:00:27.3578116
27357
63676674390
Run Code Online (Sandbox Code Playgroud)

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

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

jas*_*son 7

将代码重写为的一个真正原因

var culture = CultureInfo.CurrentCulture;
String.Format(culture, "{0} some format string", "some args"); 
String.Format(culture, "{0} some format string", "some other args"); 
Run Code Online (Sandbox Code Playgroud)

String.Format(CultureInfo.CurrentCulture, "{0} some format string", "some args");  
String.Format(CultureInfo.CurrentCulture, "{0} some format string", "some other args"); 
Run Code Online (Sandbox Code Playgroud)

是为了可读性和可维护性.现在,如果你需要某种原因,从改变文化CultureInfo.CurrentCultureCultureInfo,它通过一些配置文件加载或传递,以你只需要在一个地方更改代码的参数的方法.性能是这里的次要考虑因素,可能并不重要,因为这不太可能成为代码中的瓶颈.


Ste*_*ven 2

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