Skip to content

Comment on Which is faster? while(1) {} or while(2) {}

Comments

Interesting question. Yes, as the answers state, there is almost no reason why the two programs should iterate at different speeds, especially when the compiler optimises the loop into an unconditional jump.

However, back in the day, with some CPU architectures, and with some fairly primitive compilers, it is conceivable for while(1) and while(something) to iterate at different rates. That is if the compiler outputs literal unoptimised code, and the something is a number large enough to require a larger instruction to initialise in a register than the number 1.

For example, the 68000 CPU instruction code has a quick immediate addressing mode, which can form the moveq instruction that will embed a constant between -128 and 127 into the instruction. It also has a slower immediate addressing mode that allows full 32-bit numbers to be sourced from an extra 32 bits tacked onto the end of the instruction. Therefore, while(1) {} could conceivably be compiled to:

  label:
  moveq #1,D1
  cmpi  #0,D1
  bne   label    (branch if not equal)
whereas while(200) {} would be compiled to:
  label:
  movei #200,D1
  cmpi  #0,D1
  bne   label
and this loop would run slower than the first.

I can't recall which, but I have seen at least one compiler generate code like this (if I had to guess, I'll bet it was either Dynamic C for Rabbit 2000 or an old Bytecraft compiler for an ancient Cypress architecture). Though I've worked with a lot of old, primitive compilers & it's possible it only did this with optimizations off.

At Mindtribe, our coding style suggests "for(;;)" instead of "while(1)". However, the reason isn't performance. Instead, it's that we've seen more than one compiler produce a warning about the testing of a constant in the case of "while(1)". And we have a policy of compiling without warnings.

Depending on the CPU architecture and optimization level, there could be a host of different reasons. E.g. if you compile it to a comparison against a constant, on x86 you could go from a one byte immediate to a 4 byte immediate (if the test value is greater than 255), which could cause your loop to fall out of the loop buffer depending on what's inside the loop. If that's what the interviewer is trying to get at... this is a poor vehicle for it.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.