字符串长度昂贵

时间:2014-04-14 18:20:22

标签: c# performance

我有两个字符串值,我想总结这两个字符串的长度。如何计算最佳方式?

第一

string firstStr = "this a first message";
string secondStr = "this a second message";
int total = firstStr.Length + secondStr.Length;

第二

string firstStr = "this a first message";
string secondStr = "this a second message";
int total = (firstStr + secondStr).Length;

或其他?

6 个答案:

答案 0 :(得分:10)

第一种方式更有效,因为它只添加了两个数字。

第二种方式是浪费,因为它创建了一个新对象,将两个字符串的内容复制到其中,计算长度,然后丢弃临时对象 - 几乎不能有效地使用CPU!

比较两者的另一种方法是比较它们的渐近时间 - 第一个解的O(1)和第二个解的O(m + n)。第一次计算在恒定时间内完成,因为字符串长度很容易获得。第二个计算需要复制每个字符串的内容,这是线性的。

答案 1 :(得分:6)

首先可能更快,因为你的字符串对象已经知道他的长度。第二个是你添加连接操作。

答案 2 :(得分:2)

第二个版本正在创建一个新的字符串实例,然后获取其长度。它应该很贵。但无论差异如何,上述代码行都可以忽略不计。

答案 3 :(得分:0)

你的第一个选项不会创建一个新字符串,因此在我的书中它会更好。

int total = firstStr.Length + secondStr.Length;

答案 4 :(得分:0)

第一个更有效,因为它不涉及通过连接创建第三个字符串。 在第一种情况下,您只需要将内存中已有的两个对象的长度相加,而不会浪费内存/时间。

答案 5 :(得分:-1)

我做了几次测试运行,每次进行1M次运行

第一种方法:38,189 ms

第二种方法:50,4055 ms

这是代码:

class Program
{
    static void Main(string[] args)
    {
        Stopwatch watch;

        watch = new Stopwatch();
        watch.Start();
        First();
        watch.Stop();
        Trace.WriteLine(string.Format("first: {0} ms",watch.Elapsed.TotalMilliseconds));

        watch = new Stopwatch();
        watch.Start();
        Second();
        watch.Stop();
        Trace.WriteLine(string.Format("second: {0} ms", watch.Elapsed.TotalMilliseconds));
    }

    static void First()
    {
        for (int i = 0; i < 1000000; i++)
        {
            string firstStr = "this a first message";
            string secondStr = "this a second message";
            int total = firstStr.Length + secondStr.Length;
        }

    }

    static void Second()
    {
        for (int i = 0; i < 1000000; i++)
        {
            string firstStr = "this a first message";
            string secondStr = "this a second message";
            int total = (firstStr + secondStr).Length;
        }

    }
}
相关问题