【问题标题】:Memory allocation in string concatenation in C#C#中字符串连接中的内存分配
【发布时间】:2013-04-09 06:36:59
【问题描述】:

让,

string a = “Test”;
string b = “test 2”;
string c  = a + b

c的输出是"Testtest 2"

我想知道内存是怎么分配的?

【问题讨论】:

标签: c# memory memory-management string-concatenation


【解决方案1】:
string a = "Test";

您创建一个名为 a 的引用,并将其指向内存中的 "Test" 对象。

string b = "test 2";

您创建一个名为 b 的引用,并将其指向内存中的 “test 2” 对象。

string c  = a + b;

您正在为a + b 分配新的内存地址(并且此过程使用String.Concat 方法。)因为字符串在.NET 中是immutable。然后c 引用这个新的内存地址。

这是这个的IL代码;

  IL_0000:  nop
  IL_0001:  ldstr      "Test"
  IL_0006:  stloc.0
  IL_0007:  ldstr      "test 2"
  IL_000c:  stloc.1
  IL_000d:  ldloc.0
  IL_000e:  ldloc.1
  IL_000f:  call       string [mscorlib]System.String::Concat(string,
                                                              string)
  IL_0014:  stloc.2
  IL_0015:  ldloc.2

使用stloc.0,它将评估堆栈顶部的值存储到本地内存插槽0中。

ldstr 指令用于将字符串加载到内存或评估堆栈中。在可以使用之前,有必要将值加载到评估堆栈中。

ldloc 指令是加载本地指令。 Ldloc 将局部变量的值放入堆栈。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 2021-11-20
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2023-03-25
    相关资源
    最近更新 更多