This question讓我思考一些事情。最近,由於我一直在尋找linq pad的IL功能,我一直在比較兩種方法的IL代碼來解決同一個問題,以「確定」哪一個最好。
使用鏈接到上面的問題,有關轉換數組,我產生用於兩個答案IL代碼:
var arr = new string[] { "1", "2", "3", "4" };
var result = Array.ConvertAll(arr, s => Int32.Parse(s));
製備:
IL_0001: ldc.i4.4
IL_0002: newarr System.String
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.0
IL_000A: ldstr "1"
IL_000F: stelem.ref
IL_0010: ldloc.2
IL_0011: ldc.i4.1
IL_0012: ldstr "2"
IL_0017: stelem.ref
IL_0018: ldloc.2
IL_0019: ldc.i4.2
IL_001A: ldstr "3"
IL_001F: stelem.ref
IL_0020: ldloc.2
IL_0021: ldc.i4.3
IL_0022: ldstr "4"
IL_0027: stelem.ref
IL_0028: ldloc.2
IL_0029: stloc.0
IL_002A: ldloc.0
IL_002B: ldsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0030: brtrue.s IL_0045
IL_0032: ldnull
IL_0033: ldftn b__0
IL_0039: newobj System.Converter<System.String,System.Int32>..ctor
IL_003E: stsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0043: br.s IL_0045
IL_0045: ldsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_004A: call System.Array.ConvertAll
IL_004F: stloc.1
b__0:
IL_0000: ldarg.0
IL_0001: call System.Int32.Parse
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000A: ret
和對方的回答:
var arr = new string[] { "1", "2", "3", "4" };
var result = arr.Select(s => int.Parse(s)).ToArray();
產生:
在此IL_0001: ldc.i4.4
IL_0002: newarr System.String
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.0
IL_000A: ldstr "1"
IL_000F: stelem.ref
IL_0010: ldloc.2
IL_0011: ldc.i4.1
IL_0012: ldstr "2"
IL_0017: stelem.ref
IL_0018: ldloc.2
IL_0019: ldc.i4.2
IL_001A: ldstr "3"
IL_001F: stelem.ref
IL_0020: ldloc.2
IL_0021: ldc.i4.3
IL_0022: ldstr "4"
IL_0027: stelem.ref
IL_0028: ldloc.2
IL_0029: stloc.0
IL_002A: ldloc.0
IL_002B: ldsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0030: brtrue.s IL_0045
IL_0032: ldnull
IL_0033: ldftn b__0
IL_0039: newobj System.Func<System.String,System.Int32>..ctor
IL_003E: stsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0043: br.s IL_0045
IL_0045: ldsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_004A: call System.Linq.Enumerable.Select
IL_004F: call System.Linq.Enumerable.ToArray
IL_0054: stloc.1
b__0:
IL_0000: ldarg.0
IL_0001: call System.Int32.Parse
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000A: ret
來看,我可以告訴的是,後一種選擇
- 花費1個額外的行
- 使用LINQ時,第一答案不
- 創建詮釋的不同通過IL_0039。
問題
- 對於這個具體的例子,是我的假設是否正確?
- 一般來說,我應該如何通過IL代碼比較兩種解決方案?
- 一般來說,IL LOC較少的解決方案意味着它會更快還是使用更少的內存?
- 正如標題所說,我可以比較IL代碼以確定哪種技術更快或更好?
FWIW,我不經常這樣做,只是在工作中的開發人員之間發生一些討論時偶爾出現一次。有人會說「哦,這是更有效率」,我們會把它扔到linqpad來檢查IL代碼。此外,FWIW,我幾乎總是遵循得到它的工作之前,得到它的高效率/快速的方法。正是這樣的人不認爲我不斷比較的IL代碼是什麼我開發:)
嗨,艾倫,非常感謝你! – abatishchev 2009-08-19 11:21:02