Why pointers are faster and more efficient

c, c++, performance, pointers

Solution

That quote claims that code using pointers is faster, but it doesn't say faster than what.

The most common claim is that code using pointers is faster than equivalent code using array indices. For example:

char s[] = "hello, world";
char *p = s;
while (*p != '\0') {
    /* do something with *p */
    p ++;
}

vs.

char s[] = "hello, world";
int i = 0;
while (s[i] != '\0') {
    /* do something with s[i] */
    i ++;
}

Very old c compilers might have generated significantly faster code for the first version than for the second. For modern optimizing compilers, it's unlikely to make any difference. A good compiler might even generate exactly the same machine code for both (I haven't tested this).

It's more important to write clear C code and let the compiler generate the best machine code to implement it.

Problem

I read this in a C book : Pointers have several uses, including: • Creating fast and efficient code • Providing a convenient means for addressing many types of problems • Supporting dynamic memory allocation • Making expressions compact and succinct • Providing the ability to pass data structures by pointer without incurring a large overhead • Protecting data passed as a parameter to a function. Faster and more efficient code can be written because pointers are closer to the hardware. That is, the compiler can more easily translate the operation into machine code. There is not as much overhead associated with pointers as might be present with other operators. Q. How is 'compiler translating operations into machine code easily' related to faster working of code ? It could be easier for the compiler to convert, but how does it affect the speed of created executable ? Q. Since, everything gets converted into the machine instructions at the end, how is using pointers gonna give some special speedup if I rather pass say normal variables ? Could someone give some insight on how using pointers could make program faster ? P.S. I understand that instead of passing a massive 'object', passing a pointer would be better in terms of resources being copied, is there anything more to it because of which pointers are preferred ?

Original source