Alex Rivera | Logout

Use "greater than or equals" or just "greater than"

Asked 2008-10-23T19:41:25.627
13

I remember from C days that we were encouraged to use

i > -1

instead of

i >= 0

because of performance.

Does this still apply in the C# .NET world? What are the performance implications of using one over the other with today's compilers? i.e. Is the compiler clever enough to optimize these for you?

(As an aside try and type the question "use >= or >" into the question field on Stack Overflow and see what happens.)

Edit
Report

3 Answers

9

There is a very similar question (no criticism implied - as you say, searching for symbols is tricky) here: "Should one use < or <= in a for loop"

(Yes, I happen to be able to find it easily as I've got a lot of upvotes on my answer...)

Basically, do whatever's most readable. The day someone correctly guesses that making a change away from the most readable form is going to solve a performance problem (without the help of a profiler) is the day I stop talking about performance :)

answered 2008-10-23T19:57:56.437
3

That might have been true for some shady scripting languages that break down a >= into 2 comparisons, but whoever encouraged you to use that for C... well... you should probably try hard to forget everything they ever told you.

answered 2008-10-23T20:19:15.113
2

This reminds me of the recommendation to use ++i instead of i++ (pre-increment vs. post-increment) because it was supposedly one instruction faster. (I forget where I originally read about this, but it was probably C/C++ Users' Journal or Dr. Dobb's Journal but I can't seem to find a web reference.)

I seriously doubt that > or >= is faster or slower; instead write your code for clarity.

As a side note, I developed a preference for the pre-increment (++i) operator even if the reason is now potentially outdated.

answered 2008-10-23T20:56:44.383

Your Answer