c# string 的一点点理解和实践
工作8个月了,也天天看很多的技术文章,可就是感觉自己没有时间写点自己的理解,总以为有那时间应该再看点书.
今天,不知道怎么的想明白了,开始写博客,写个开篇.
根据标题,先从下边的两行说起.
string test1 = "Hello "
+ "world!";
string test2 = "Hello";
test2 += "world";
想到这两行代码的时候,我就在想它们有什么不同,于是翻出ildasm来,看到这些
IL_003a: ldstr "Hello world!" //test1编译时候已经加在一起了 IL_003f: stloc.1 IL_0040: ldstr "Hello" IL_0045: stloc.2 IL_0046: ldloc.2 IL_0047: ldstr "world" IL_004c: call string [mscorlib]System.String::Concat(string, string) //test2是运行时候调用string.Concat连接在一起的
再看程序的metainfo,更说明了这个问题
User Strings
-------------------------------------------------------
7000003d : (12) L"Hello world!"
70000057 : ( 5) L"Hello"
70000063 : ( 5) L"world"
考虑到字符串驻留机制,test1的写法更值得推荐.
反面例子如下
string test1 = "hello " + "world"; //注意双引号里边的空格位置string test2 = "hello" + " world";string test3 = "hello "; test3 += "world";string test4 = "hello"; test4 = " world";
metainfo
User Strings
-------------------------------------------------------
7000003d : (11) L"hello world"
70000055 : ( 6) L"hello "
70000063 : ( 5) L"world"
7000006f : ( 5) L"hello"
7000007b : ( 6) L" world"
很明显,第一种写法会在一定程序上减少程序的体积,提高程序的运行效率.
恩,,再YY一下,,难道是"细节决定成败"的那个"细节"?

浙公网安备 33010602011771号