【发布时间】:2014-04-07 02:50:06
【问题描述】:
这里有两种结果相同的方法:
public class MessageManager
{
public void SendMessage(string name, int count)
{
string message = "Hi " + name + ". I know you don't like cake, so I bought you " + count + " lollipops. Same thing, right?"; // No boxing. "count" was converted to string somehow.
//Console.WriteLine(message);
}
public void SendMessage2(string name, int count)
{
string message = String.Format("Hi {0}. I know you don't like cake, so I bought you {1} lollipops. Same thing, right?", name, count); // Boxing "name" and "count" + executing unnecessary code.
//Console.WriteLine(message);
}
}
所以我猜第二种方法会比第一种方法慢,因为装箱和执行 String.Format() 方法中的一些额外代码。
我用以下方法测试过它们:
public static class PerformanceTester
{
public static TimeSpan TestAction(Action<string, int> action)
{
Stopwatch timer = new Stopwatch();
timer.Start();
for (ushort i = 0; i < ushort.MaxValue; i++)
action("Alex", 1000);
timer.Stop();
return timer.Elapsed;
}
}
这是它的用法:
static void Main(string[] args)
{
MessageManager mm = new MessageManager();
TimeSpan ts_m1 = PerformanceTester.TestAction(new Action<string, int>(mm.SendMessage));
TimeSpan ts_m2 = PerformanceTester.TestAction(new Action<string, int>(mm.SendMessage2));
Console.WriteLine("First message took time: " + ts_m1.ToString());
Console.WriteLine("Second message took time: " + ts_m2.ToString());
Console.ReadKey();
}
使用我的英特尔® 酷睿™2 双核处理器 E8200(调试)的输出:
使用我的英特尔® 酷睿™2 双核处理器 E8200(发布)的输出:
我看到 String.Format 几乎无处不在(指南、博客、教程等),但它实际上比简单的字符串连接要慢。我知道当我谈论 C# 时,我一定不会关心性能,但是这个例子中的结果太棒了。 问题是:“是否有任何最佳实践,String.Format 实际上比字符串串联更好。”
【问题讨论】:
-
它是发布版本吗?如果是这样,csc不会对其进行优化并删除完全没有任何副作用的代码吗?
-
字符串连接是最快的,但会消耗一些内存。 String.format 代码很难阅读(如果您考虑代码的可读性)。这实际上是您想要实现的目标。你必须为另一个妥协。这里有很好的讨论michaelmerrell.com/2011/11/…
-
@zerkms 它正在调试。我现在也添加了版本。
-
@Pierre-LucPineault 在那里找不到我的问题的答案。问题是:“是否有任何最佳实践 String.Format 实际上比字符串串联更好。”
-
@Wallstrider 如果您想要最佳实践,请使用Code Review。