请问C#做常量字符串连接任何编译时优化?如果是这样,怎么我必须通过代码写入到充分利用这一点?

例:如何将这些比较在运行时

Console.WriteLine("ABC" + "DEF");

const string s1 = "ABC";
Console.WriteLine(s1 + "DEF");

const string s1 = "ABC";
const string s2 = s1 + "DEF";
Console.WriteLine(s2);
有帮助吗?

解决方案

是,它的作用。可以使用通过使用ildasm或反射器来检查码验证这一点。

static void Main(string[] args) {
    string s = "A" + "B";
    Console.WriteLine(s);
}

被翻译成

.method private hidebysig static void  Main(string[] args) cil managed {
    .entrypoint
    // Code size       17 (0x11)
    .maxstack  1
    .locals init ([0] string s)
    IL_0000:  nop
    IL_0001:  ldstr      "AB" // note that "A" + "B" is concatenated to "AB"
    IL_0006:  stloc.0
    IL_0007:  ldloc.0
    IL_0008:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000d:  nop
    IL_000e:  br.s       IL_0010
    IL_0010:  ret
} // end of method Program::Main

也有一些是更有趣,但有关这种情况发生。如果有一个字符串在装配字面,CLR将仅创建一个对象在组件相同文字的所有实例。

因此:

static void Main(string[] args) {
    string s = "A" + "B";
    string t = "A" + "B";
    Console.WriteLine(Object.ReferenceEquals(s, t)); // prints true!
}

将打印“真”在控制台上!这种优化被称为串实习

其他提示

根据反射

Console.WriteLine("ABCDEF");
Console.WriteLine("ABCDEF");
Console.WriteLine("ABCDEF");

即使在调试配置。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top