close
文章出處

C#字符串連接常用的四種方式:StringBuilder、+、string.Format、List<string>。

1.+的方式

string sql = "update tableName set int1=" + int1.ToString() + ",int2=" + int2.ToString() + ",int3=" + int3.ToString() + " where id=" + id.ToString();

編譯器會優化為:

string sql = string.Concat(new string[] { "update tableName set int1=", int1.ToString(), ",int2=", int2.ToString(), ",int3=", int3.ToString(), " where id=", id.ToString() });

下面是string.Concat的實現:

public static string Concat(params string[] values)
{
    int totalLength = 0;
    if (values == null)
    {
        throw new ArgumentNullException("values");
    }
    string[] strArray = new string[values.Length];
    for (int i = 0; i < values.Length; i++)
    {
        string str = values[i];
        strArray[i] = (str == null) ? Empty : str;
        totalLength += strArray[i].Length;
        if (totalLength < 0)
        {
            throw new OutOfMemoryException();
        }
    }
    return ConcatArray(strArray, totalLength);
}
private static string ConcatArray(string[] values, int totalLength)
{
    string dest = FastAllocateString(totalLength);
    int destPos = 0;
    for (int i = 0; i < values.Length; i++)
    {
        FillStringChecked(dest, destPos, values[i]);
        destPos += values[i].Length;
    }
    return dest;
}
private static unsafe void FillStringChecked(string dest, int destPos, string src)
{
    int length = src.Length;
    if (length > (dest.Length - destPos))
    {
        throw new IndexOutOfRangeException();
    }
    fixed (char* chRef = &dest.m_firstChar)
    {
        fixed (char* chRef2 = &src.m_firstChar)
        {
            wstrcpy(chRef + destPos, chRef2, length);
        }
    }

}

先計算目標字符串的長度,然后申請相應的空間,最后逐一復制,時間復雜度為o(n),常數為1。固定數量的字符串連接效率最高的是+。但是字符串的連+不要拆成多條語句,比如:

string sql = "update tableName set int1=";
sql += int1.ToString();
sql += ...

這樣的代碼,不會被優化為string.Concat,就變成了性能殺手,因為第i個字符串需要復制n-i次,時間復雜度就成了o(n^2)。

2.StringBuilder的方式

如果字符串的數量不固定,就用StringBuilder,一般情況下它使用2n的空間來保證o(n)的整體時間復雜度,常數項接近于2。

因為這個算法的實用與高效,.net類庫里面有很多動態集合都采用這種犧牲空間換取時間的方式,一般來說效果還是不錯的。

3.string.Format的方式

它的底層是StringBuilder,所以其效率與StringBuiler相似。

4.List<string>它可以轉換為string[]后使用string.Concat或string.Join,很多時候效率比StringBuiler更高效。List與StringBuilder采用的是同樣的動態集合算法,時間復雜度也是O(n),與StringBuilder不同的是:List的n是字符串的數量,復制的是字符串的引用;StringBuilder的n是字符串的長度,復制的數據。不同的特性決定的它們各自的適應環境,當子串比較大時建議使用List<string>,因為復制引用比復制數據劃算。而當子串比較小,比如平均長度小于8,特別是一個一個的字符,建議使用StringBuilder。


總結

1>固定數量的字符串連接+的效率是最高的;

2>當字符串的數量不固定,并且子串的長度小于8,用StringBuiler的效率高些。

3>當字符串的數量不固定,并且子串的長度大于8,用List<string>的效率高些。 


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 AutoPoster 的頭像
    AutoPoster

    互聯網 - 大數據

    AutoPoster 發表在 痞客邦 留言(0) 人氣()