使用CultureInfo.CurrentCulture
格式化字符串时,我正在使用string.format
引用this blog
所以根据这个作者
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更加昂贵。