使用string.format
性能考虑多次
这只是有暗示,如果 您正在使用的CurrentCulture很多在格式化我的字符串时,我使用
CultureInfo.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
性能比使用本地变量(与作者浏览矛盾)更好。或者我在这里错过了什么?
编辑:我没有重新设置秒表之前的第二次迭代。因此有所不同。重置秒表,更新迭代计数和更新结果在这个编辑
在您的测试代码中,您不会重置秒表。使用缓存的引用实际上更快。 – Steven 2010-02-08 17:04:22
CultureInfo.CurrentCulture并不便宜,但string.Format更昂贵。 – Steven 2010-02-08 17:09:05
史蒂文,你说得对,我没有重新设置秒表。为什么不把它作为答案发布,我会更新我的帖子+标记为答案。对于那些很好奇的人来说,使用局部变量会更快。对于1亿次迭代,相差大约2.473秒! – ram 2010-02-08 17:13:32