【发布时间】:2011-10-26 16:53:08
【问题描述】:
C#代码:
string first = "A";
first += "B";
first += "C";
string second = "D" + "E" + "F";
生成的 IL 代码:
.locals init ([0] string first,
[1] string second)
IL_0000: nop
IL_0001: ldstr "A"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldstr "B"
IL_000d: call string [mscorlib]System.String::Concat(string,
string)
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ldstr "C"
IL_0019: call string [mscorlib]System.String::Concat(string,
string)
IL_001e: stloc.0
IL_001f: ldstr "DEF"
IL_0024: stloc.1
IL_0025: ret
很明显,内联连接效率更高一些,因为它只调用了一次 ldstr,但还有其他区别(例如在内存中创建的字符串对象?)
谢谢
【问题讨论】:
-
它也从不调用
String.Concat()。 -
关于主题codinghorror.com/blog/2009/01/…的有用阅读
-
这绝对是因为编译器意识到“D”、“E”和“F”是常量,可以在编译时而不是在运行时一起滚动。
-
@JesseC.Slicer 是的,在每种情况下都将
const放在string之前并查看编译器错误会很快显示这一点; “D”+“E”+“F”是一个常量表达式。不过,还有更多值得研究的地方。