Re: array index and pointer, which is faster?



Xiaohan wrote:
p is an array and N is a large number. Which of the following two
loops is faster?

Case1:

for(i=0; i<N; i++){
p[i] = i;
}

Case2:

for(i=0; i<N; i++){
*p = i;
p++;
}

It seems that Case 1 needs multiplication/shifting to calculate the
address/index and the second case needs only an ADD operation.

Neither case "needs" anything like that. The compiler is free to interpret this code anyway it likes, as long as the observable behavior of the program satisfies the requirements imposed by the language specification. Thats' the only thing it "needs".

But I
tested it, the speed is almost the same. Can anybody tell me why?

Well, take a look at the assembly code you quoted. Don't you see that it is exactly the same in both cases?

A typical compiler doesn't necessarily think in terms of individual C operations. It doesn't try to translate each C operation into its exact analogue in machine language, as you seem to believe. The compiler normally tries to see the bigger picture - what your code really does - and then choses the most optimal way to implement the requested functionality in machine language. Of course its capabilities are limited and sometimes its behavior might seem (and actually be) illogical.

In your case the compiler was smart enough to realize that both versions of the code do exactly the same thing (in terms of the observable behavior of the program), so it translated them into identical machine code - the one it considers to be the most optimal.

--
Best regards,
Andrey Tarasevich
.