开发者

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开发者_StackOverflow中文版 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜