1. 程式人生 > >C# 字符串拼接性能探索 c#中+、string.Concat、string.Format、StringBuilder.Append四種方式進行字符串拼接時的性能

C# 字符串拼接性能探索 c#中+、string.Concat、string.Format、StringBuilder.Append四種方式進行字符串拼接時的性能

ant runt info lap tel ole 3.2 ons empty

本文通過ANTS Memory Profiler工具探索c#中+、string.Concat、string.Format、StringBuilder.Append四種方式進行字符串拼接時的性能。

本文涉及程序為.NET Core 2.0控制臺應用程序。

一、常量字符串拼接

技術分享圖片 技術分享圖片
private static void TestPerformance(Action action, int times)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for(int i = 0; i < times; i++)
            {
                action();
            }
            sw.Stop();
            Console.WriteLine(action.Method.Name + ", FullTime: " + sw.ElapsedMilliseconds);
        }
技術分享圖片

1.+方法

1.1連續拼接

技術分享圖片
private static void AddTest()
        {
            string s = string.Empty;
            s = "1" + "2" + "3" + "4" + "5" + "6" + "7" + "8";
        }

運行時間:

技術分享圖片

內存情況:

技術分享圖片技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  AddTest() cil managed
{
  // Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0005:  pop
  IL_0006:  ret
} // end of method Program::AddTest
技術分享圖片

1.2分段拼接

技術分享圖片 技術分享圖片
private static void AddWithParamTest2()
        {
            string s = string.Empty;
            s += "1";
            s += "2";
            s += "3";
            s += "4";
            s += "5";
            s += "6";
            s += "7";
            s += "8";
        }
技術分享圖片

運行時間:

技術分享圖片

內存情況:

技術分享圖片

技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  AddWithParamTest2() cil managed
{
  // Code size       87 (0x57)
  .maxstack  2
  IL_0000:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0005:  ldstr      "1"
  IL_000a:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_000f:  ldstr      "2"
  IL_0014:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0019:  ldstr      "3"
  IL_001e:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0023:  ldstr      "4"
  IL_0028:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_002d:  ldstr      "5"
  IL_0032:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0037:  ldstr      "6"
  IL_003c:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0041:  ldstr      "7"
  IL_0046:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_004b:  ldstr      "8"
  IL_0050:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0055:  pop
  IL_0056:  ret
} // end of method Program::AddWithParamTest2
技術分享圖片

通過IL代碼可以看出,分段的+=代碼調用的是Concat方法,並且比連續的+多開辟了許多內存空間。

2.Concat方法

2.1分次Concat

技術分享圖片 技術分享圖片
private static void ConcatTest()
        {
            string s = string.Empty;
            s = string.Concat(s, "1");
            s = string.Concat(s, "2");
            s = string.Concat(s, "3");
            s = string.Concat(s, "4");
            s = string.Concat(s, "5");
            s = string.Concat(s, "6");
            s = string.Concat(s, "7");
            s = string.Concat(s, "8");
        }
技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  AddWithParamTest2() cil managed
{
  // Code size       87 (0x57)
  .maxstack  2
  IL_0000:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0005:  ldstr      "1"
  IL_000a:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_000f:  ldstr      "2"
  IL_0014:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0019:  ldstr      "3"
  IL_001e:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0023:  ldstr      "4"
  IL_0028:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_002d:  ldstr      "5"
  IL_0032:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0037:  ldstr      "6"
  IL_003c:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0041:  ldstr      "7"
  IL_0046:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_004b:  ldstr      "8"
  IL_0050:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0055:  pop
  IL_0056:  ret
} // end of method Program::AddWithParamTest2
技術分享圖片

可見IL代碼與+分段拼接常量字符串相同,性能相似。

2.2Concat一次拼接常量字符串

技術分享圖片
private static void ConcatTest2()
        {
            string s = string.Empty;
            string.Concat(s, "1", "2", "3", "4", "5", "6", "7", "8");           
        }

運行時間:

技術分享圖片

內存情況:

技術分享圖片技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  ConcatTest2() cil managed
{
  // Code size       88 (0x58)
  .maxstack  4
  .locals init (string V_0)
  IL_0000:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0005:  stloc.0
  IL_0006:  ldc.i4.s   9
  IL_0008:  newarr     [System.Runtime]System.String
  IL_000d:  dup
  IL_000e:  ldc.i4.0
  IL_000f:  ldloc.0
  IL_0010:  stelem.ref
  IL_0011:  dup
  IL_0012:  ldc.i4.1
  IL_0013:  ldstr      "1"
  IL_0018:  stelem.ref
  IL_0019:  dup
  IL_001a:  ldc.i4.2
  IL_001b:  ldstr      "2"
  IL_0020:  stelem.ref
  IL_0021:  dup
  IL_0022:  ldc.i4.3
  IL_0023:  ldstr      "3"
  IL_0028:  stelem.ref
  IL_0029:  dup
  IL_002a:  ldc.i4.4
  IL_002b:  ldstr      "4"
  IL_0030:  stelem.ref
  IL_0031:  dup
  IL_0032:  ldc.i4.5
  IL_0033:  ldstr      "5"
  IL_0038:  stelem.ref
  IL_0039:  dup
  IL_003a:  ldc.i4.6
  IL_003b:  ldstr      "6"
  IL_0040:  stelem.ref
  IL_0041:  dup
  IL_0042:  ldc.i4.7
  IL_0043:  ldstr      "7"
  IL_0048:  stelem.ref
  IL_0049:  dup
  IL_004a:  ldc.i4.8
  IL_004b:  ldstr      "8"
  IL_0050:  stelem.ref
  IL_0051:  call       string [System.Runtime]System.String::Concat(string[])
IL_0056: stloc.0
IL_0057: ret
} // end of method Program::ConcatTest2
技術分享圖片

通過IL代碼可以看出,string.Concat(s, s1, s2, s3)並不調用String.Concat方法,而是直接在堆棧上進行操作。因為需要局部變量來標記,比分次調用Concat方法所占的內存要多一些。

3.Format方法

3.1一次Format

技術分享圖片
private static void FormatTest()
        {
            string s = string.Empty;
            s = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}", "1", "2", "3", "4", "5", "6", "7", "8");
        }

運行時間:

技術分享圖片

內存情況:

技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  FormatTest() cil managed
{
  // Code size       88 (0x58)
  .maxstack  5
  IL_0000:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0005:  pop
  IL_0006:  ldstr      "{0}{1}{2}{3}{4}{5}{6}{7}"
  IL_000b:  ldc.i4.8
  IL_000c:  newarr     [System.Runtime]System.Object
  IL_0011:  dup
  IL_0012:  ldc.i4.0
  IL_0013:  ldstr      "1"
  IL_0018:  stelem.ref
  IL_0019:  dup
  IL_001a:  ldc.i4.1
  IL_001b:  ldstr      "2"
  IL_0020:  stelem.ref
  IL_0021:  dup
  IL_0022:  ldc.i4.2
  IL_0023:  ldstr      "3"
  IL_0028:  stelem.ref
  IL_0029:  dup
  IL_002a:  ldc.i4.3
  IL_002b:  ldstr      "4"
  IL_0030:  stelem.ref
  IL_0031:  dup
  IL_0032:  ldc.i4.4
  IL_0033:  ldstr      "5"
  IL_0038:  stelem.ref
  IL_0039:  dup
  IL_003a:  ldc.i4.5
  IL_003b:  ldstr      "6"
  IL_0040:  stelem.ref
  IL_0041:  dup
  IL_0042:  ldc.i4.6
  IL_0043:  ldstr      "7"
  IL_0048:  stelem.ref
  IL_0049:  dup
  IL_004a:  ldc.i4.7
  IL_004b:  ldstr      "8"
  IL_0050:  stelem.ref
  IL_0051:  call       string [System.Runtime]System.String::Format(string,
                                                                    object[])
  IL_0056:  pop
  IL_0057:  ret
} // end of method Program::FormatTest
技術分享圖片

StringFormat方法雖然是基於StringBuilder,但由於需要遍歷字符串來識別占位符,所以比較慢。

3.2Format分次拼接

技術分享圖片 技術分享圖片
private static void FormatTest2()
        {
            string s = string.Empty;
            s = string.Format("{0}{1}", s, "1");
            s = string.Format("{0}{1}", s, "2");
            s = string.Format("{0}{1}", s, "3");
            s = string.Format("{0}{1}", s, "4");
            s = string.Format("{0}{1}", s, "5");
            s = string.Format("{0}{1}", s, "6");
            s = string.Format("{0}{1}", s, "7");
            s = string.Format("{0}{1}", s, "8");
        }
技術分享圖片

運行時間:

技術分享圖片

內存情況:

技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  FormatTest2() cil managed
{
  // Code size       143 (0x8f)
  .maxstack  3
  .locals init (string V_0)
  IL_0000:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0005:  stloc.0
  IL_0006:  ldstr      "{0}{1}"
  IL_000b:  ldloc.0
  IL_000c:  ldstr      "1"
  IL_0011:  call       string [System.Runtime]System.String::Format(string,
                                                                    object,
                                                                    object)
  IL_0016:  stloc.0
  IL_0017:  ldstr      "{0}{1}"
  IL_001c:  ldloc.0
  IL_001d:  ldstr      "2"
  IL_0022:  call       string [System.Runtime]System.String::Format(string,
                                                                    object,
                                                                    object)
  IL_0027:  stloc.0
  IL_0028:  ldstr      "{0}{1}"
  IL_002d:  ldloc.0
  IL_002e:  ldstr      "3"
  IL_0033:  call       string [System.Runtime]System.String::Format(string,
                                                                    object,
                                                                    object)
  IL_0038:  stloc.0
  IL_0039:  ldstr      "{0}{1}"
  IL_003e:  ldloc.0
  IL_003f:  ldstr      "4"
  IL_0044:  call       string [System.Runtime]System.String::Format(string,
                                                                    object,
                                                                    object)
  IL_0049:  stloc.0
  IL_004a:  ldstr      "{0}{1}"
  IL_004f:  ldloc.0
  IL_0050:  ldstr      "5"
  IL_0055:  call       string [System.Runtime]System.String::Format(string,
                                                                    object,
                                                                    object)
  IL_005a:  stloc.0
  IL_005b:  ldstr      "{0}{1}"
  IL_0060:  ldloc.0
  IL_0061:  ldstr      "6"
  IL_0066:  call       string [System.Runtime]System.String::Format(string,
                                                                    object,
                                                                    object)
  IL_006b:  stloc.0
  IL_006c:  ldstr      "{0}{1}"
  IL_0071:  ldloc.0
  IL_0072:  ldstr      "7"
  IL_0077:  call       string [System.Runtime]System.String::Format(string,
                                                                    object,
                                                                    object)
  IL_007c:  stloc.0
  IL_007d:  ldstr      "{0}{1}"
  IL_0082:  ldloc.0
  IL_0083:  ldstr      "8"
  IL_0088:  call       string [System.Runtime]System.String::Format(string,
                                                                    object,
                                                                    object)
  IL_008d:  stloc.0
  IL_008e:  ret
} // end of method Program::FormatTest2
技術分享圖片

分次使用Format方法拼接字符串,即分次調用Format方法,多次循環遍歷字符串,耗時更長。

4.StringBuilder方法

技術分享圖片 技術分享圖片
private static void BuilderTest()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("1");
            sb.Append("2");
            sb.Append("3");
            sb.Append("4");
            sb.Append("5");
            sb.Append("6");
            sb.Append("7");
            sb.Append("8");
        }
技術分享圖片

運行時間:

技術分享圖片

內存情況:

技術分享圖片技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  BuilderTest() cil managed
{
  // Code size       101 (0x65)
  .maxstack  3
  IL_0000:  newobj     instance void [System.Runtime]System.Text.StringBuilder::.ctor()
  IL_0005:  dup
  IL_0006:  ldstr      "1"
  IL_000b:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_0010:  pop
  IL_0011:  dup
  IL_0012:  ldstr      "2"
  IL_0017:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_001c:  pop
  IL_001d:  dup
  IL_001e:  ldstr      "3"
  IL_0023:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_0028:  pop
  IL_0029:  dup
  IL_002a:  ldstr      "4"
  IL_002f:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_0034:  pop
  IL_0035:  dup
  IL_0036:  ldstr      "5"
  IL_003b:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_0040:  pop
  IL_0041:  dup
  IL_0042:  ldstr      "6"
  IL_0047:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_004c:  pop
  IL_004d:  dup
  IL_004e:  ldstr      "7"
  IL_0053:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_0058:  pop
  IL_0059:  ldstr      "8"
  IL_005e:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_0063:  pop
  IL_0064:  ret
} // end of method Program::BuilderTest
技術分享圖片

在短字符串大量拼接的測試中,可以看出一次使用+進行拼接所耗內存最少,所用時間最短。其余方式所耗內存相差不大,但StringBuilder所耗時間明顯較短。

由於Format方法內部存在對字符串的遍歷,可以推測,隨著字符串的長度變長,Format方法所耗時間將會增加。

二、字符串變量拼接(多次循環拼接)

技術分享圖片 技術分享圖片
private static void TestPerformanceWithParam<T>(Action<T> action, T t, int times)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < times; i++)
            {
                action(t);
            }
            sw.Stop();
            Console.WriteLine(action.Method.Name + ", FullTime: " + sw.ElapsedMilliseconds);
        }
技術分享圖片

1.+方法

1.1連續拼接

技術分享圖片
private static void AddTest(string t)
        {
            string s = string.Empty;
            s = t + t + t + t + t + t + t + t;
        }

運行時間:

技術分享圖片

內存情況:

技術分享圖片技術分享圖片

IL代碼:

技術分享圖片 技術分享圖片
.method private hidebysig static void  AddTest(string t) cil managed
{
  // Code size       51 (0x33)
  .maxstack  8
  IL_0000:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0005:  pop
  IL_0006:  ldc.i4.8
  IL_0007:  newarr     [System.Runtime]System.String
  IL_000c:  dup
  IL_000d:  ldc.i4.0
  IL_000e:  ldarg.0
  IL_000f:  stelem.ref
  IL_0010:  dup
  IL_0011:  ldc.i4.1
  IL_0012:  ldarg.0
  IL_0013:  stelem.ref
  IL_0014:  dup
  IL_0015:  ldc.i4.2
  IL_0016:  ldarg.0
  IL_0017:  stelem.ref
  IL_0018:  dup
  IL_0019:  ldc.i4.3
  IL_001a:  ldarg.0
  IL_001b:  stelem.ref
  IL_001c:  dup
  IL_001d:  ldc.i4.4
  IL_001e:  ldarg.0
  IL_001f:  stelem.ref
  IL_0020:  dup
  IL_0021:  ldc.i4.5
  IL_0022:  ldarg.0
  IL_0023:  stelem.ref
  IL_0024:  dup
  IL_0025:  ldc.i4.6
  IL_0026:  ldarg.0
  IL_0027:  stelem.ref
  IL_0028:  dup
  IL_0029:  ldc.i4.7
  IL_002a:  ldarg.0
  IL_002b:  stelem.ref
  IL_002c:  call       string [System.Runtime]System.String::Concat(string[])
  IL_0031:  pop
  IL_0032:  ret
} // end of method Program::AddTest
技術分享圖片

從IL代碼可見,在使用+連續拼接字符串變量時,內部調用了String.Concat(string[])方法。

1.2分段拼接

技術分享圖片 技術分享圖片
private static void AddWithParamTest2(string t)
        {
            string s = string.Empty;
            s += t;
            s += t;
            s += t;
            s += t;
            s += t;
            s += t;
            s += t;
            s += t;
        }
技術分享圖片

運行時間:

技術分享圖片

內存情況:

技術分享圖片技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  AddWithParamTest2(string t) cil managed
{
  // Code size       55 (0x37)
  .maxstack  8
  IL_0000:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0005:  ldarg.0
  IL_0006:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_000b:  ldarg.0
  IL_000c:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0011:  ldarg.0
  IL_0012:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0017:  ldarg.0
  IL_0018:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_001d:  ldarg.0
  IL_001e:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0023:  ldarg.0
  IL_0024:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0029:  ldarg.0
  IL_002a:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_002f:  ldarg.0
  IL_0030:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0035:  pop
  IL_0036:  ret
} // end of method Program::AddWithParamTest2
技術分享圖片

2.Concat方法

2.1分次concat

IL代碼:

技術分享圖片
.method private hidebysig static void  ConcatTest(string t) cil managed
{
  // Code size       55 (0x37)
  .maxstack  8
  IL_0000:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0005:  ldarg.0
  IL_0006:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_000b:  ldarg.0
  IL_000c:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0011:  ldarg.0
  IL_0012:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0017:  ldarg.0
  IL_0018:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_001d:  ldarg.0
  IL_001e:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0023:  ldarg.0
  IL_0024:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0029:  ldarg.0
  IL_002a:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_002f:  ldarg.0
  IL_0030:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_0035:  pop
  IL_0036:  ret
} // end of method Program::ConcatTest
技術分享圖片

從IL代碼來看,同使用+分段拼接相似。

2.2一次拼接

IL代碼:

技術分享圖片
.method private hidebysig static void  ConcatTest2(string t) cil managed
{
  // Code size       56 (0x38)
  .maxstack  4
  .locals init (string V_0)
  IL_0000:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0005:  stloc.0
  IL_0006:  ldc.i4.s   9
  IL_0008:  newarr     [System.Runtime]System.String
  IL_000d:  dup
  IL_000e:  ldc.i4.0
  IL_000f:  ldloc.0
  IL_0010:  stelem.ref
  IL_0011:  dup
  IL_0012:  ldc.i4.1
  IL_0013:  ldarg.0
  IL_0014:  stelem.ref
  IL_0015:  dup
  IL_0016:  ldc.i4.2
  IL_0017:  ldarg.0
  IL_0018:  stelem.ref
  IL_0019:  dup
  IL_001a:  ldc.i4.3
  IL_001b:  ldarg.0
  IL_001c:  stelem.ref
  IL_001d:  dup
  IL_001e:  ldc.i4.4
  IL_001f:  ldarg.0
  IL_0020:  stelem.ref
  IL_0021:  dup
  IL_0022:  ldc.i4.5
  IL_0023:  ldarg.0
  IL_0024:  stelem.ref
  IL_0025:  dup
  IL_0026:  ldc.i4.6
  IL_0027:  ldarg.0
  IL_0028:  stelem.ref
  IL_0029:  dup
  IL_002a:  ldc.i4.7
  IL_002b:  ldarg.0
  IL_002c:  stelem.ref
  IL_002d:  dup
  IL_002e:  ldc.i4.8
  IL_002f:  ldarg.0
  IL_0030:  stelem.ref
  IL_0031:  call       string [System.Runtime]System.String::Concat(string[])
  IL_0036:  stloc.0
  IL_0037:  ret
} // end of method Program::ConcatTest2
技術分享圖片

從IL代碼可以看出,同使用+一次拼接相似。

3.Format

技術分享圖片
private static void FormatTest(string t)
        {
            string s = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}", t, t, t, t, t, t, t, t);
        }

運行時間:

技術分享圖片

內存情況:

技術分享圖片技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  FormatTest(string t) cil managed
{
  // Code size       50 (0x32)
  .maxstack  8
  IL_0000:  ldstr      "{0}{1}{2}{3}{4}{5}{6}{7}"
  IL_0005:  ldc.i4.8
  IL_0006:  newarr     [System.Runtime]System.Object
  IL_000b:  dup
  IL_000c:  ldc.i4.0
  IL_000d:  ldarg.0
  IL_000e:  stelem.ref
  IL_000f:  dup
  IL_0010:  ldc.i4.1
  IL_0011:  ldarg.0
  IL_0012:  stelem.ref
  IL_0013:  dup
  IL_0014:  ldc.i4.2
  IL_0015:  ldarg.0
  IL_0016:  stelem.ref
  IL_0017:  dup
  IL_0018:  ldc.i4.3
  IL_0019:  ldarg.0
  IL_001a:  stelem.ref
  IL_001b:  dup
  IL_001c:  ldc.i4.4
  IL_001d:  ldarg.0
  IL_001e:  stelem.ref
  IL_001f:  dup
  IL_0020:  ldc.i4.5
  IL_0021:  ldarg.0
  IL_0022:  stelem.ref
  IL_0023:  dup
  IL_0024:  ldc.i4.6
  IL_0025:  ldarg.0
  IL_0026:  stelem.ref
  IL_0027:  dup
  IL_0028:  ldc.i4.7
  IL_0029:  ldarg.0
  IL_002a:  stelem.ref
  IL_002b:  call       string [System.Runtime]System.String::Format(string,
                                                                    object[])
  IL_0030:  pop
  IL_0031:  ret
} // end of method Program::FormatTest
技術分享圖片

時間的損耗主要來自於String.Format方法。

4.StringBuilder方法

技術分享圖片 技術分享圖片
private static void BuilderTest(string t)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(t);
            sb.Append(t);
            sb.Append(t);
            sb.Append(t);
            sb.Append(t);
            sb.Append(t);
            sb.Append(t);
            sb.Append(t);
        }
技術分享圖片

運行時間:

技術分享圖片

內存情況:

技術分享圖片技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  BuilderTest(string t) cil managed
{
  // Code size       69 (0x45)
  .maxstack  3
  IL_0000:  newobj     instance void [System.Runtime]System.Text.StringBuilder::.ctor()
  IL_0005:  dup
  IL_0006:  ldarg.0
  IL_0007:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_000c:  pop
  IL_000d:  dup
  IL_000e:  ldarg.0
  IL_000f:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_0014:  pop
  IL_0015:  dup
  IL_0016:  ldarg.0
  IL_0017:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_001c:  pop
  IL_001d:  dup
  IL_001e:  ldarg.0
  IL_001f:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_0024:  pop
  IL_0025:  dup
  IL_0026:  ldarg.0
  IL_0027:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_002c:  pop
  IL_002d:  dup
  IL_002e:  ldarg.0
  IL_002f:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_0034:  pop
  IL_0035:  dup
  IL_0036:  ldarg.0
  IL_0037:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_003c:  pop
  IL_003d:  ldarg.0
  IL_003e:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_0043:  pop
  IL_0044:  ret
} // end of method Program::BuilderTest
技術分享圖片

在短字符串(上面所用字符串為“short”)大量循環拼接(上述結果為每個方法循環執行一千萬次)時,四種方法的差距並不明顯。

當字符串變長後,可見運行結果差距拉大:

技術分享圖片

此時StringBuilder仍沒有明顯的優勢。

三、字符串變量拼接(循環拼接至一個字符串)

1.+方法

技術分享圖片 技術分享圖片
private static void TestAddVeryLong(string s, int times)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            string str = string.Empty;
            for(int i = 0; i < times; i++)
            {
                str += s;
            }
            sw.Stop();
            Console.WriteLine("add very long: " + sw.ElapsedMilliseconds);
        }
技術分享圖片

運行時間:

技術分享圖片

內存情況:

技術分享圖片技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  TestAddVeryLong(string s,
                                                       int32 times) cil managed
{
  // Code size       71 (0x47)
  .maxstack  2
  .locals init (class [System.Runtime.Extensions]System.Diagnostics.Stopwatch V_0,
           string V_1,
           int32 V_2)
  IL_0000:  newobj     instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::.ctor()
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  callvirt   instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::Start()
  IL_000c:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0011:  stloc.1
  IL_0012:  ldc.i4.0
  IL_0013:  stloc.2
  IL_0014:  br.s       IL_0022
  IL_0016:  ldloc.1
  IL_0017:  ldarg.0
  IL_0018:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_001d:  stloc.1
  IL_001e:  ldloc.2
  IL_001f:  ldc.i4.1
  IL_0020:  add
  IL_0021:  stloc.2
  IL_0022:  ldloc.2
  IL_0023:  ldarg.1
  IL_0024:  blt.s      IL_0016
  IL_0026:  ldloc.0
  IL_0027:  callvirt   instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::Stop()
  IL_002c:  ldstr      "add very long: "
  IL_0031:  ldloc.0
  IL_0032:  callvirt   instance int64 [System.Runtime.Extensions]System.Diagnostics.Stopwatch::get_ElapsedMilliseconds()
  IL_0037:  box        [System.Runtime]System.Int64
  IL_003c:  call       string [System.Runtime]System.String::Concat(object,
                                                                    object)
  IL_0041:  call       void [System.Console]System.Console::WriteLine(string)
  IL_0046:  ret
} // end of method Program::TestAddVeryLong
技術分享圖片

2.Concat方法

技術分享圖片 技術分享圖片
private static void TestConcatVeryLong(string s, int times)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            string str = string.Empty;
            for (int i = 0; i < times; i++)
            {
                str = string.Concat(str, s);
            }
            sw.Stop();
            Console.WriteLine("concat very long: " + sw.ElapsedMilliseconds);
        }
技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  TestConcatVeryLong(string s,
                                                          int32 times) cil managed
{
  // Code size       71 (0x47)
  .maxstack  2
  .locals init (class [System.Runtime.Extensions]System.Diagnostics.Stopwatch V_0,
           string V_1,
           int32 V_2)
  IL_0000:  newobj     instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::.ctor()
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  callvirt   instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::Start()
  IL_000c:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0011:  stloc.1
  IL_0012:  ldc.i4.0
  IL_0013:  stloc.2
  IL_0014:  br.s       IL_0022
  IL_0016:  ldloc.1
  IL_0017:  ldarg.0
  IL_0018:  call       string [System.Runtime]System.String::Concat(string,
                                                                    string)
  IL_001d:  stloc.1
  IL_001e:  ldloc.2
  IL_001f:  ldc.i4.1
  IL_0020:  add
  IL_0021:  stloc.2
  IL_0022:  ldloc.2
  IL_0023:  ldarg.1
  IL_0024:  blt.s      IL_0016
  IL_0026:  ldloc.0
  IL_0027:  callvirt   instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::Stop()
  IL_002c:  ldstr      "concat very long: "
  IL_0031:  ldloc.0
  IL_0032:  callvirt   instance int64 [System.Runtime.Extensions]System.Diagnostics.Stopwatch::get_ElapsedMilliseconds()
  IL_0037:  box        [System.Runtime]System.Int64
  IL_003c:  call       string [System.Runtime]System.String::Concat(object,
                                                                    object)
  IL_0041:  call       void [System.Console]System.Console::WriteLine(string)
  IL_0046:  ret
} // end of method Program::TestConcatVeryLong
技術分享圖片

由IL代碼可見,和使用+性能相似。

3.Format方法

技術分享圖片 技術分享圖片
private static void TestFormatVeryLong(string s, int times)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            string str = string.Empty;
            for (int i = 0; i < times; i++)
            {
                str = string.Format("{0}{1}", str, s);
            }
            sw.Stop();
            Console.WriteLine("format very long: " + sw.ElapsedMilliseconds);
        }
技術分享圖片

運行時間:

技術分享圖片

內存情況:

技術分享圖片技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  TestFormatVeryLong(string s,
                                                          int32 times) cil managed
{
  // Code size       76 (0x4c)
  .maxstack  3
  .locals init (class [System.Runtime.Extensions]System.Diagnostics.Stopwatch V_0,
           string V_1,
           int32 V_2)
  IL_0000:  newobj     instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::.ctor()
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  callvirt   instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::Start()
  IL_000c:  ldsfld     string [System.Runtime]System.String::Empty
  IL_0011:  stloc.1
  IL_0012:  ldc.i4.0
  IL_0013:  stloc.2
  IL_0014:  br.s       IL_0027
  IL_0016:  ldstr      "{0}{1}"
  IL_001b:  ldloc.1
  IL_001c:  ldarg.0
  IL_001d:  call       string [System.Runtime]System.String::Format(string,
                                                                    object,
                                                                    object)
  IL_0022:  stloc.1
  IL_0023:  ldloc.2
  IL_0024:  ldc.i4.1
  IL_0025:  add
  IL_0026:  stloc.2
  IL_0027:  ldloc.2
  IL_0028:  ldarg.1
  IL_0029:  blt.s      IL_0016
  IL_002b:  ldloc.0
  IL_002c:  callvirt   instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::Stop()
  IL_0031:  ldstr      "format very long: "
  IL_0036:  ldloc.0
  IL_0037:  callvirt   instance int64 [System.Runtime.Extensions]System.Diagnostics.Stopwatch::get_ElapsedMilliseconds()
  IL_003c:  box        [System.Runtime]System.Int64
  IL_0041:  call       string [System.Runtime]System.String::Concat(object,
                                                                    object)
  IL_0046:  call       void [System.Console]System.Console::WriteLine(string)
  IL_004b:  ret
} // end of method Program::TestFormatVeryLong
技術分享圖片

4.StringBuilder方法

技術分享圖片 技術分享圖片
private static void TestBuilderVeryLong(string s, int times)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < times; i++)
            {
                sb.Append(s);
            }
            sw.Stop();
            Console.WriteLine("builder very long: " + sw.ElapsedMilliseconds);
        }
技術分享圖片

運行時間:

技術分享圖片

內存情況:

技術分享圖片技術分享圖片

IL代碼:

技術分享圖片
.method private hidebysig static void  TestBuilderVeryLong(string s,
                                                           int32 times) cil managed
{
  // Code size       71 (0x47)
  .maxstack  2
  .locals init (class [System.Runtime.Extensions]System.Diagnostics.Stopwatch V_0,
           class [System.Runtime]System.Text.StringBuilder V_1,
           int32 V_2)
  IL_0000:  newobj     instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::.ctor()
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  callvirt   instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::Start()
  IL_000c:  newobj     instance void [System.Runtime]System.Text.StringBuilder::.ctor()
  IL_0011:  stloc.1
  IL_0012:  ldc.i4.0
  IL_0013:  stloc.2
  IL_0014:  br.s       IL_0022
  IL_0016:  ldloc.1
  IL_0017:  ldarg.0
  IL_0018:  callvirt   instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(string)
  IL_001d:  pop
  IL_001e:  ldloc.2
  IL_001f:  ldc.i4.1
  IL_0020:  add
  IL_0021:  stloc.2
  IL_0022:  ldloc.2
  IL_0023:  ldarg.1
  IL_0024:  blt.s      IL_0016
  IL_0026:  ldloc.0
  IL_0027:  callvirt   instance void [System.Runtime.Extensions]System.Diagnostics.Stopwatch::Stop()
  IL_002c:  ldstr      "builder very long: "
  IL_0031:  ldloc.0
  IL_0032:  callvirt   instance int64 [System.Runtime.Extensions]System.Diagnostics.Stopwatch::get_ElapsedMilliseconds()
  IL_0037:  box        [System.Runtime]System.Int64
  IL_003c:  call       string [System.Runtime]System.String::Concat(object,
                                                                    object)
  IL_0041:  call       void [System.Console]System.Console::WriteLine(string)
  IL_0046:  ret
} // end of method Program::TestBuilderVeryLong
技術分享圖片

這個差距在拼接字符串更多的時候會更加明顯。

拼接一千萬次時,+方法運行一個多小時仍無法得出結果:

技術分享圖片

而StringBuilder只需要102ms。

技術分享圖片

+方法的問題在於由於string的特殊性,每次操作都將新開辟內存空間,隨著字符串長度的增加、操作次數的增加等,+方法所耗費的內存會越來越大。

而StringBuilder則可以在原有的內存空間中進行修改和擴張,在進行頻繁、長串的操作時極大地提高了效率。

顯然,如果是不頻繁、短字符串的拼接,使用哪種方式拼接字符串沒有明顯的性能差別(Format可能稍差一些),但如果是頻繁的長串操作,StringBuilder具有絕對的優勢。

C# 字符串拼接性能探索 c#中+、string.Concat、string.Format、StringBuilder.Append四種方式進行字符串拼接時的性能