Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why looping over array using array indexing is slower than that of pointer access?

Tags:

arrays

c

pointers

I'm reading Kochan's book "Programming in C". In section Pointer and Arrays on p. 264 he says:

In general, the process of indexing an array takes more time to execute than does the process of accessing the contents of a pointer. In fact, this is one of the main reasons why pointers are used to access the elements of an array—the code that is generated is generally more efficient. Of course, if access to the array is not generally sequential, pointers accomplish nothing, as far as this issue is concerned, because the expression *(pointer + j) takes just as long to execute as does the expression array[j].

Can someone explain what is faster than what ? Specifically, if speed of array[j] = speed of *(pointer + j) then what is the process of indexing an array and what is the process of accessing the contents of a pointer ? Also, there are questions and answers on SO that mention that array[j] is converted to *(array+j) during compilation so there shouldn't be any difference.

Summary: Please give me a very simple example of what Kochan says. 2 pieces of code and point at faster one, don't have to explain why it is true.

like image 223
Maciej Szpakowski Avatar asked Oct 07 '14 16:10

Maciej Szpakowski


1 Answers

Look at the snippet

int arr[5] = {0};
int *p = arr;
int c = 1;

Now, see the loop 1:

for(int i = 0; i < 5; i++)
     arr[i] = c++ + 1;

loop 2:

for(int i = 0; i < 5; i++)
     *p++ = c++ + 1; 

The difference between these two loops is their body. First loop contains arr[i] = c++ + 1. This is equivalent to *(arr + i) = c++ + 1. What does it mean by *(arr + i)?
It means that:

  • Fetch the base pointer address.
  • Fetch the value of i
  • Add the value of i to the base address.
  • Dereference the final address.

While in case of second loop's body *p++ means:

  • Fetch the value of p
  • Dereference the address before incrementing it.
  • Increment the address by 1.

Of course second one will execute faster. But, now a days modern compilers are smart enough to optimize these codes and most probably you will get the same result for both loop.

like image 190
haccks Avatar answered Oct 01 '22 00:10

haccks