Alex Rivera | Logout

What is faster (x < 0) or (x == -1)?

Asked 2009-05-26T19:26:02.570
38

Variable x is int with possible values: -1, 0, 1, 2, 3. Which expression will be faster (in CPU ticks):

1. (x < 0)
2. (x == -1)

Language: C/C++, but I suppose all other languages will have the same.

P.S. I personally think that answer is (x < 0).

More widely for gurus: what if x from -1 to 2^30?

Edit
Report

1 Answer

7

It could be dependent on what operations precede or succeed the comparison. For example, if you assign a value to x just before doing the comparison, then it might be faster to check the sign flag than to compare to a specific value. Or the CPU's branch-prediction performance could be affected by which comparison you choose.

But, as others have said, this is dependent upon CPU architecture, memory architecture, compiler, and a lot of other things, so there is no general answer.

answered 2009-05-26T20:59:42.397

Your Answer