简体   繁体   中英

Optimal way to negate a floating point value in C#

What is faster from a code execution perspective:

double a = 1.234;
double minus_a = -a;

or:

double a = 1.234;
double minus_a = a * -1;

Does the second case actually perform floating point multiplication? Or is the compiler smart enough to optimize the second case to be the same as the first?

Tested with the 64bit JIT of .NET 4, other JITs such as the old 32bit JIT or the newer RyuJIT can be different (actually the 32bit old JIT must do something else since it does not use SSE)

-x translates into

vmovsd      xmm1,qword ptr [00000050h] ; there's a -0.0 there, so only the sign bit is set
vxorpd      xmm0,xmm0,xmm1 ; literally flip the sign

x * -1 into

vmulsd      xmm0,xmm0,mmword ptr [00000048h] ; -1.0

Yes, very literal.

As for speed, you can pick your model from here and compare, but vxorpd will always be faster than vmulsd .

Could it have optimized x * -1 to a XOR? The behavior for NaN is different, with the XOR approach flipping the sign of the NaN, but that doesn't really matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM