【发布时间】:2011-01-14 11:02:53
【问题描述】:
我在使用string.format 格式化我的字符串时使用CultureInfo.CurrentCulture
这只是暗示如果 你经常使用 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 属性比使用局部变量更好(这与作者的观点相矛盾)。还是我在这里遗漏了什么?
编辑:我没有在第二次迭代之前重置秒表。因此差异。重置秒表,更新迭代计数并导致此编辑
【问题讨论】:
-
在您的测试代码中,您不会重置秒表。使用缓存的引用实际上更快。
-
CultureInfo.CurrentCulture 并不便宜,但 string.Format 更昂贵。
-
史蒂文,你说得对,我没有重置秒表。您为什么不将其发布为答案,我将更新我的帖子+将您的帖子标记为答案。对于那些好奇的人,是的,使用局部变量会更快。 1亿次迭代相差约2.473秒!!!
-
+1 这是你的一个非常有趣的问题,Ram。为了支持你的观点,我在 SO 上的某处读到访问属性比私有不可变成员更昂贵。
标签: c# performance optimization properties