4 ms·
Not necessarily so if you come from a strong Assembly language background. Most processors have a special instruction for incrementing a register that's shorte
by spc476 11y ago
Not necessarily so if you come from a strong Assembly language background. Most processors have a special instruction for incrementing a register that's shorter (and faster) than the more generic ADD instruction.
For instance, on a 64-bit x86 machine,
ADD RAX,1
is nine bytes long, while
INC RAX
is one byte. Maybe not as much a win these days, but back when memory was smaller and more expensive, it was worth it.
- cballard 11y agoIn a high-level language, this is the job of the compiler, though. If the compiler isn't generating those instructions for cases where the increment can be proven to be 1, I would consider it a bug.
- DiThi 11y agoNowadays, a compiler that doesn't optimize a "+1" is a bad compiler.
- spc476 11y agoThese days yes. But when C was first being developed, when you might have had 64K of memory for everything? Back then it might have been a sane choice.
- JoeAltmaier 11y agoDoesn't x86 machine code have short-immediate forms? So ADD RAX,1 could be 4 or 5 bytes. Still a win to use INC of course.
- throwaway999888 11y agoAny optimising compiler for a mainstream language that can't do this optimisation reliably in this day and age is crap.
- mattst88 11y agoCompiling #include <stdint.h> uint64_t inc(uint64_t x) { return x + 1; } With -O0 gives me: 48 83 c0 01 add $0x1,%rax and with -O2: 48 8d 47 01 lea 0x1(%rdi),%rax That is, both are four bytes.