-1

I wrote a simple for loop like this.

for(int i = 0; i != 100; i++) 

then someone gave an opinion that it should be

for(int i = 0; i < 100; i++) 

When this turns into assembly mine should turn into Jump on Equality JNE and the latter should be Jump if Greater JG. Or the compiler will do something completely different and it will both turn into the same thing.

Anyway which one is more correct, i find the first one more logically correct because it is known that i WILL pass 100, the greater than check seems logically reduntant. Also are JNE and JG as fast as each other?

user936509
  • 213
  • 3
  • 8
  • 3
    Unless you have an unbelieveably stupid compiler, don't worry about it. The compiler writers probably thought about this way more thoroughly than you did. – In silico Mar 13 '12 at 05:21
  • Well that's premature optimization anyway. Why is that so important? – Etienne de Martel Mar 13 '12 at 05:21
  • Did you try looking at what your compiler output for each case? – Carl Norum Mar 13 '12 at 05:21
  • 1
    possible duplicate of [What is faster (x < 0) or (x == -1)?](http://stackoverflow.com/questions/912256/what-is-faster-x-0-or-x-1) – Xeo Mar 13 '12 at 05:22
  • What i see is a potential for i to be accidently greater than 100 and the loop running forever if one uses the != 100 instead of < 100. – Beached Mar 13 '12 at 13:53

2 Answers2

2

For this case, there's no practical difference between using < and !=. Many iterators, however, don't define < comparisons, only != or ==, in which case those are your only real choice.

jne and jg will normally be the same speed. You might observe differences in speed between the two, but if so they're likely to stem from things like cache usage, not the instructions themselves.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

I don't think you'll find system where there is a performance differences for your particular case (measure to verify).

Most of the code uses i < count condition in for loop. So it will take less time for most people to read code with < condition compared to !=.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179