Wasn't it at some stage, with x86 assembly at least, that a comparison with zero (jump-zero instruction) was faster than comparing with any arbitrary integer? This could have had (aeons ago) an effect in looping through an (edit: zero-index)-array (and preferring the backwards loop) ?
It actually depends on the machine implementation. A forward loop from 0 to N-1 may end up with assembler code similar to this pseudo-code:
mov r1,0 // sometimes, xor r1,r1 needs less program space and/ +or time mov r2,N loop: // do something with r1 inc r1 // may or may not set flags, depending on the impleme +ntation cmp r1,r2 // often imlemented as sub r1,r2 but without actually + writing the result back to the register, just setting flags jne loop // if implemented as sub r1,r2, jne (jump if not rqua +l) is equal to jnz (jump if not zero)
If the machine allows compare with a constant, one register may be sufficient:
xor r1,r1 loop: // do something with r1 inc r1 cmp r1,N jne loop
The same loop running backwards from N down to 1 may be more efficient IF the decrement operation sets the zero flag:
mov r1,N loop: // do something with r1 dec r1 // must set/clear zero flag depending on value of r1 jnz loop
On the Z80, there is a special instruction DJNZ (decrement B and jump if non-zero) for exactly this purpose. It does not even affect the flags, it's all handled internally. The 8051 also has a DJNZ that can work on memory or a choosen register. The x86 processors have LOOP/LOOPE/LOOPNE. LOOP is like DJNZ using CX, ECX or RCX, LOOPE and LOOPNE additionally check the zero flag.
x86 processors have the REP/REPZ/REPNZ prefixes for a similar purpose. It repeats the follwing string instruction until CX/ECX/RCX is zero. REPZ also aborts if the zero flag is cleared, REPNZ also aborts if the zero flag is set. String operations are INS (read from I/O port to memory), MOVS (copy memory, i.e. memcpy, strcpy), OUTS (write from memory to I/O port), LODS (read from memory to accumulator), STOS (write accumulator to memory, i.e. memset), CMPS (compare memory, i.e. strcmp, memcmp), SCAS (compare memory to accumulator, i.e. strchr, strlen).
Alexander
In reply to Re^2: I prefer my indexes to start at:
by afoken
in thread I prefer my indexes to start at:
by Arunbear
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |