考虑以下代码。's' 被分成两次到两个不同的数组。
string s = "1,2,3";
string[] arr = s.Split(',');
string[] arr2 = s.Split(',');
foreach (..)
{ // do something
}
在发布模式下编译时,IL 看起来像这样,因此 Split 实际上被调用了两次。有没有优化的原因?
IL_0008: newarr [mscorlib]System.Char
IL_000d: stloc.s CS$0$0000
IL_000f: ldloc.s CS$0$0000
IL_0011: ldc.i4.0
IL_0012: ldc.i4.s 44
IL_0014: stelem.i2
IL_0015: ldloc.s CS$0$0000
IL_0017: callvirt instance string[] [mscorlib]System.String::Split(char[])
IL_001c: stloc.1
IL_001d: ldloc.0
IL_001e: ldc.i4.1
IL_001f: newarr [mscorlib]System.Char
IL_0024: stloc.s CS$0$0001
IL_0026: ldloc.s CS$0$0001
IL_0028: ldc.i4.0
IL_0029: ldc.i4.s 44
IL_002b: stelem.i2
IL_002c: ldloc.s CS$0$0001
IL_002e: callvirt instance string[] [mscorlib]System.String::Split(char[])