加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – stringbuilder与string concat

发布时间:2020-12-15 17:44:56 所属栏目:百科 来源:网络整理
导读:在我的项目中,我循环了一个dataview结果. string html =string.empty; DataView dV = data.DefaultView; for(int i=0;i dV.Count;i++) { DataRowView rv = dV[i]; html += rv.Row["X"].Tostring(); } dV中的行数将为3或4. 在这种情况下使用字符串concat = op
在我的项目中,我循环了一个dataview结果.
string html =string.empty;
 DataView dV = data.DefaultView;
 for(int i=0;i< dV.Count;i++)
 {
     DataRowView rv = dV[i];
     html += rv.Row["X"].Tostring();
 }

dV中的行数将为3或4.

在这种情况下使用字符串concat = opearator或StringBuilder更好,为什么?

解决方法

我会在这里使用StringBuilder,只是因为它描述了你在做什么.

对于3或4个字符串的简单连接,它可能不会有任何显着差异,字符串连接甚至可能稍快一些 – 但是如果您错了并且有很多行,则StringBuilder将开始更高效,它总是更加描述你正在做什么.

或者,使用以下内容:

string html = string.Join("",dv.Cast<DataRowView>()
                                .Select(rv => rv.Row["X"]));

请注意,您目前的字符串之间没有任何分隔符.你确定这是你想要的吗? (另请注意,你的代码在当前没有什么意义 – 你没有在循环中使用我,为什么?)

我有一个article about string concatenation,更详细地介绍了为什么值得使用StringBuilder和什么时候.

编辑:对于那些怀疑字符串连接可以更快的人来说,这是一个测试 – 故意“讨厌”的数据,但只是为了证明这是可能的:

using System;
using System.Diagnostics;
using System.Text;

class Test
{
    static readonly string[] Bits = { 
        "small string","string which is a bit longer","stirng which is longer again to force yet another copy with any luck"
    };

    static readonly int ExpectedLength = string.Join("",Bits).Length;

    static void Main()        
    {
        Time(StringBuilderTest);
        Time(ConcatenateTest);
    }

    static void Time(Action action)
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        // Make sure it's JITted
        action();
        Stopwatch sw = Stopwatch.StartNew();
        for (int i = 0; i < 10000000; i++)
        {
            action();
        }
        sw.Stop();
        Console.WriteLine("{0}: {1} millis",action.Method.Name,(long) sw.Elapsed.TotalMilliseconds);
    }

    static void ConcatenateTest()
    {
        string x = "";
        foreach (string bit in Bits)
        {
            x += bit;
        }
        // Force a validation to prevent dodgy optimizations
        if (x.Length != ExpectedLength)
        {
            throw new Exception("Eek!");
        }
    }

    static void StringBuilderTest()
    {
        StringBuilder builder = new StringBuilder();
        foreach (string bit in Bits)
        {
            builder.Append(bit);
        }
        string x = builder.ToString();
        // Force a validation to prevent dodgy optimizations
        if (x.Length != ExpectedLength)
        {
            throw new Exception("Eek!");
        }
    }
}

我的机器上的结果(用/ o / debug-编译):

StringBuilderTest: 2245 millis
ConcatenateTest: 989 millis

我已经运行了好几次,包括反转测试的顺序,结果是一致的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读