gpt4 book ai didi

c# - 多次使用属性时的性能考虑

转载 作者:太空狗 更新时间:2023-10-29 22:20:58 26 4
gpt4 key购买 nike

在使用 string.format 格式化我的字符串时,我正在使用 CultureInfo.CurrentCulture

引用this blog

This just has the implication that if you are using CurrentCulture a lot, it might be worth reading it into a private variable rather than making lots of calls to CultureInfo.CurrentCulture, otherwise you're using up clock cycles needlessly.

根据作者的说法

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 属性比使用局部变量要好(这与作者的观点相矛盾)。或者我在这里遗漏了什么?

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

最佳答案

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

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,它通过某些配置文件加载或作为方法传递给您的参数只需要更改一个地方的代码。 这里性能是次要考虑因素,可能无关紧要,因为这不太可能成为您代码中的瓶颈。

关于c# - 多次使用属性时的性能考虑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2223248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com