扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
class Program { static void Main(string[] args) { String s = "a"; s = "abcd"; } } |
01 .method private hidebysig static void Main(string[] args) cil managed 02 { 03 .entrypoint 04 // 代码大小 14 (0xe) 05 .maxstack 1 06 .locals init ([0] string s) 07 IL_0000: nop 08 IL_0001: ldstr "a" 09 IL_0006: stloc.0 10 IL_0007: ldstr "abcd" 11 IL_000c: stloc.0 12 IL_000d: ret 13 } // end of method Program::Main |
String s = "a"; s = "abcd"; |
.locals init ([0] string s1) IL_0000: nop IL_0001: ldstr "ab" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldstr "cd" IL_000d: call string [mscorlib]System.String::Concat(string, string) IL_0012: stloc.0 IL_0013: ret |
.locals init ([0] string s1) IL_0000: nop IL_0001: ldstr "abcd" IL_0006: stloc.0 IL_0007: ret |
可以很清楚地看到,第(1)段代码将导致String类的Concat()方法被调用(实现字串加法运算)。对于第(2)段代码,由于C#编译器聪明地在编译时直接将两个字串合并为一个字串字面量,所以程序运行时CLR只调用一次ldstr指令就完成了所有工作,其执行速度谁快就不言而喻了!
3、避免使用加法运算符连接不同类型的数据
请看以下代码:
String str = "100+100=" + 200; Console.Writeline(str); |
.maxstack 2 .locals init ([0] string str) IL_0000: nop IL_0001: ldstr "100+100=" IL_0006: ldc.i4 0xc8 IL_000b: box [mscorlib]System.Int32 IL_0010: call string [mscorlib]System.String::Concat(object, object) IL_0015: stloc.0 IL_0016: ldloc.0 IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ret |
String str = "100+100="; Console.Write(str); Console.WriteLine(200); |
.maxstack 1 .locals init ([0] string str) IL_0000: nop IL_0001: ldstr "100+100=" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call void [mscorlib]System.Console::Write(string) IL_000d: nop IL_000e: ldc.i4 0xc8 IL_0013: call void [mscorlib]System.Console::WriteLine(int32) IL_0018: nop IL_0019: ret |
String str =""; for (int i = 1; i <= 10; i++) { str += i; if(i<10) str += "+"; } |
//预先分配1K的内存空间 StringBuilder sb = new StringBuilder(1024); for (int i = 1; i <= 10; i++) { sb.Append(i); if(i<10) sb.Append("+"); } String result = sb.ToString(); |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。