views:

54

answers:

2

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.

+2  A: 

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.

SLaks
@Brian - see http://msdn.microsoft.com/en-us/library/74z9b11e(VS.95).aspx for more information on what the `CompareTo` method is doing.
ChrisF
The less operations the cpu has to perform the better.
Gary Willoughby
+3  A: 

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.

0xA3