Brian Triplett
Brian Triplett

Reputation: 3532

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.

Upvotes: 3

Views: 1357

Answers (2)

Dirk Vollmar
Dirk Vollmar

Reputation: 176219

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.

Upvotes: 4

SLaks
SLaks

Reputation: 887777

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.

Upvotes: 2

Related Questions