C# 多次使用属性时的性能考虑
使用C# 多次使用属性时的性能考虑,c#,performance,optimization,properties,C#,Performance,Optimization,Properties,使用string.format 引用 这就意味着如果 您经常使用CurrentCulture,它 也许值得一读 私有变量,而不是 打了很多电话给 CultureInfo.CurrentCulture,否则为 你的时钟周期快用完了 不必要的 那么按照笔者的说法, var culture = CultureInfo.CurrentCulture string.Format(culture,"{0} some format string","some args"); string.Format(cul
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");
比
string.Format(CultureInfo.CurrentCulture,"{0} some format string","some args");
string.Format(CultureInfo.CurrentCulture,"{0} some format string","some other args");
根据MSDN
多次访问某个属性时是否存在相关的性能损失
我还做了一些实证分析,测试表明使用局部变量比直接使用属性更昂贵
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);
我的测试表明,使用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");
从
是为了可读性和可维护性。现在,如果出于某种原因需要将区域性从
CultureInfo.CurrentCulture
更改为CultureInfo
,该区域性通过某个配置文件加载或作为方法传递到参数,则只需在一个位置更改代码性能是次要考虑因素,可能并不重要,因为这不太可能成为代码中的瓶颈。代码中有一个bug。在测试代码中,不重置秒表。当您重置秒表时,您将看到使用缓存的引用实际上更快。CultureInfo.CurrentCulture并不便宜,但是string.Format要贵得多。在测试代码中,您不需要重置秒表。使用缓存引用实际上更快。CultureInfo.CurrentCulture并不便宜,但string.Format的成本更高。Steven,你说得对,我没有重置秒表。你为什么不把它作为一个答案贴出来,我会更新我的帖子+把你的作为答案标记。对于那些好奇的人来说,是的,使用局部变量更快。对于1亿次迭代,相差约2.473秒+这是你的一个非常有趣的问题,拉姆。为了支持你的观点,我已经读到了一些关于访问属性比私有不可变成员更昂贵的内容。
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");