小编m_d*_*p29的帖子

哪个字符串连接操作更快 - "+"或string.Concat

我一直在阅读不同的答案,其中字符串连接操作更好.我读到某处"+"内部调用string.Concat方法,string.Concat两者之间更快.当我查看IL代码时,它似乎没有提出上述陈述.

对于

string s1 = "1" + "2";
Run Code Online (Sandbox Code Playgroud)

IL代码

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       8 (0x8)
  .maxstack  1
  .locals init ([0] string s1)
  IL_0000:  nop
  IL_0001:  ldstr      "12"
  IL_0006:  stloc.0
  IL_0007:  ret
} // end of method Program::Main
Run Code Online (Sandbox Code Playgroud)

另外,我从IL代码中注意到"+"只初始化一个字符串,而string.Concat初始化两个字符串以连接.我也试过多个字符串.在使用内存方面,"+"似乎只使用一个字符串变量,而另一个选项在内部使用更多变量.

对于,

string s1 = string.concat("1", "2");
Run Code Online (Sandbox Code Playgroud)

IL代码

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       18 (0x12)
  .maxstack  2
  .locals init ([0] …
Run Code Online (Sandbox Code Playgroud)

.net c# string

2
推荐指数
2
解决办法
437
查看次数

标签 统计

.net ×1

c# ×1

string ×1