[英]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.