[英]Is there any performance gain from using type suffixes in C#?
有時有必要使用類型后綴(例如, 0d用於值為零的對偶或0f用於浮點),通常被認為是好的樣式。
但這對性能有影響嗎?
所以打電話幾百萬次
if (x == 0d) ... or
if (x == 0.0) ...
會和
if (x == 0) ...
我想,編譯器將一次將0轉換為0.0,因此對性能無關緊要。 但是由於我幾次在質量代碼中看到它,所以我不確定...
由於注釋而添加:x不是int為其double。
如果檢查IL代碼,則與int
到0.0
文字進行比較時,會發現其他conv
操作代碼
int x = 0;
Console.WriteLine (x == 0.0);
IL_0000: ldc.i4.0
IL_0001: stloc.0 // x
IL_0002: ldloc.0 // x
IL_0003: conv.r8 //<-- this is absent if literal is 0
IL_0004: ldc.r8 00 00 00 00 00 00 00 00
IL_000D: ceq
IL_000F: call System.Console.WriteLine
這是事實, Int32
==
運算符重載接受int
作為第二個參數。
備注: 使用編譯器優化標志LINQPad編譯。
一個重要的說法是直到您確定這是瓶頸,才進行納米優化。 這樣的優化通常會破壞代碼的可讀性,並因此導致可維護性。
在Ilya Ivanov的提示下,我檢查了一個小樣本程序的IL代碼。
Ilya假設x是一個整數,如果是這種情況,他對轉換的評論絕對正確(conv.r8)。 但是我想到的情況是,如果將double類型的變量與double常量進行比較。 在這種情況下,類型后綴有什么區別嗎?
答案是不!
讓我們看一下這個小程序,比較(d == 0)或(d == 0d):
static void Main(string[] args)
{
double d = 0.0;
if (d == 0) // if (d == 0d)
d = 1.23;
Console.WriteLine(d);
}
兩種版本都編譯成完全相同的IL代碼:
.method private hidebysig static
void Main (
string[] args
) cil managed
{
// Method begins at RVA 0x2050
// Code size 48 (0x30)
.maxstack 2
.entrypoint
.locals init (
[0] float64 d,
[1] bool CS$4$0000
)
IL_0000: nop
IL_0001: ldc.r8 0.0
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldc.r8 0.0
IL_0015: ceq
IL_0017: ldc.i4.0
IL_0018: ceq
IL_001a: stloc.1
IL_001b: ldloc.1
IL_001c: brtrue.s IL_0028
IL_001e: ldc.r8 1.23
IL_0027: stloc.0
IL_0028: ldloc.0
IL_0029: call void [mscorlib]System.Console::WriteLine(float64)
IL_002e: nop
IL_002f: ret
} // end of method Program::Main
當然,匯編代碼也相同。
所以寫0而不是0.0或0d很好...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.