多次使用属性时的性能考虑因素

我在使用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是一个属性

多次访问属性时是否存在性能损失?

我还做了一些经验分析,我的测试表明,使用局部变量比直接使用属性更昂贵。

 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要贵得多。

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

 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 ,或者作为方法传递给参数,则只需在一个位置更改代码即可。 性能是这里的次要考虑因素,可能并不重要,因为这不太可能成为代码中的瓶颈。

如果探查器将其显示为代码中的重要问题,并且放入局部变量使其更快,则应该仅将CultureInfo.CurrentCulture优化为局部变量。 此配置文件显示两者都不是真的所以我不会把它放到本地。