简体   繁体   中英

Comparison of floating point types

Are there any performance differences between

 float x, y;
 // Set x and y
 if(x > y)
 {
    // do something
 }

and

 float x,y;
 // Set x and y
 if(x.CompareTo(y) > 0)
 {
    // do something
 }

Are they doing the same thing behind the scenes or is there more to it. I have a piece of performance critical code that does this comparison many, many times and I wanted to check that there wasn't more going on than I thought.

The following is a general remark, disregarding performance. You should be aware that there is a slight difference between using the operator and the IComparable method. They are almost doing the same. The difference is when both your values are NaN and you are checking for equality. See the following example:

float x = float.NaN;
float y = float.NaN;

bool resultOperator = (x == y);               // will be false
bool resultCompareTo = (x.CompareTo(y) == 0); // will be true(!)

The reason for this inconsistency is that the the IComparable interface requires that x.CompareTo(x) returns zero.

The first one will be a little bit faster and a lot more readable.

x > y compiles to an IL instruction that compares two values on the stack.

x.CompareTo(y) > 0 compiles to a normal method call followed by a comparison, which will be a little bit slower.

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