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.)
No, there are no performance issues associated with comparison operators. And any good compiler would optimize something this trivial anyway.
I’m not sure where you got the suggestion to use ‘i > -1’ rather than ‘i >= 0’. On the x86 architecture, it makes no difference which you use: either case takes exactly two instructions… one to compare and one to jump:
On most RISC architectures that I know, ‘i >= 0’ may actually be faster since there is usually a dedicated zero register, and ‘i > -1’ may require loading a constant. For example, MIPS only has a < instruction (no <=). Here is how the two constructs would be (naively!) expressed in MIPS assembly language:
So in the naive, general case, it will actually be one instruction faster to do ‘i >= 0’ on MIPS. Of course, RISC code is so heavily optimizable that a compiler would likely change either of these instruction sequences almost beyond recognition 🙂
So… the short answer is no no no, no difference.