[Solved] What code is more CPU expensive: while(*p) or while(i–)? [closed]


*pointer nominally requires a fetch from memory, and that is generally the most expensive of the operations shown in your code.

If we assume your code is compiled directly to the obvious assembly corresponding to the operations as they are described in C’s abstract machine, with no optimization, modern CPUs for desktop computers are typically capable of executing one loop iteration per cycle, except for the memory access. That is, they can increment a pointer or counter, test its value, and branch, with a throughput of one set of those per cycle.

When these operations are used in real programs, they will usually be dwarfed by the other operations being performed. Compilers are generally so good at optimization that the method used to express the loop iteration and termination has little effect on the performance—optimization will likely produce equivalent code regardless of variations in expression for differences like incrementing a counter versus iterating a pointer to some end value. (This excludes using a pointer to fetch a value from memory for testing. That does raise complications.)

2

solved What code is more CPU expensive: while(*p) or while(i–)? [closed]