连接多个字符串与String.Format

时间:2014-04-07 02:50:07

标签: c# string

以下是两种结果相同的方法:

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(DEBUG)输出:

string_test

使用我的英特尔®酷睿™2双核处理器E8200(RELEASE)输出: enter image description here

我看到几乎所有地方都使用了String.Format(指南,博客,教程等),但它实际上比简单的字符串连接慢。我知道当我谈论C#时我不应该关心性能,但是这个例子中的结果太棒了。 问题是:“有没有最好的做法,其中String.Format实际上比串联连接更好。”

2 个答案:

答案 0 :(得分:3)

这主要是风格问题。但是,请考虑更复杂的格式。例如,你想格式化一堆东西:

var s = String.Format("{0,10:N2}  {1,-20}  {2:P2}", val, description, (val/100));

或......

var s = val.ToString("10:N2") + string.Format("{0,-20}", desc) + (val/100).ToString("P2");

我更喜欢那里的String.Format电话。它将格式与内容分开,就像CSS将表示与HTML内容分开一样。当我编写或检查格式化输出的代码时,我通常希望一目了然地看到格式。在调试格式问题时,格式化的实际值无关紧要。

通过连接,我不得不通过单个值来查看每个项目的格式。

最后,性能真的很重要吗?大多数程序花费很少的时间格式化他们的输出优化格式代码似乎是浪费时间。写下任何更容易维护和证明正确的内容。

答案 1 :(得分:2)

string.format就像格式化字符串一样。您可以使用格式字符串并将其粘贴到资源中或将其翻译。它与性能无关,与可读性无关。简单的字符串连接是可以的,如果你说小于5,如果你想连接更多的字符串并想要考虑性能 - 使用StringBuilder。

相关问题