Some people said: "Any operation that can be achieved by array subscripting can also be done with pointers. The pointer version will in general be faster".
I doubt about the outcome of the above, so I do the following test:
In the following article, We do not care compiler optimization. About compiler optimization how to affect the efficiency between pointer and array, please note: Efficiency: arrays vs pointers
(Visual Studio 2010, Debug Mode, no optimizations)
#include <windows.h>
#include <stdio.h>
int main()
{
int a[] = {10,20,30};
int* ap = a;
long counter;
int start_time, end_time;
int index;
start_time = GetTickCount();
for (counter = 1000000000L; counter>0; counter--)
{
*(ap+1) = 100;
}
end_time = GetTickCount();
printf("10 billion times of *ap = %d\n", end_time-start_time);
start_time = GetTickCount();
for (counter = 1000000000L; counter>0; counter--)
{
a[1] = 101;
}
end_time = GetTickCount();
printf("10 billion times of a[0] = %d\n", end_time-start_time);
return 0;
}
the result is:
10 billion times of *ap = 3276
10 billion times of a[0] = 3541
The pointer seems to be a little fast. But after I compared the dis-assemble, I fell into a deeper confusion。
(Visual Studio 2010, Debug Mode, no optimizations)
; 17 : *(ap+1) = 100;
mov eax, DWORD PTR _ap$[ebp]
mov DWORD PTR [eax+4], 100 ; 00000064H
; 25 : a[1] = 101;
mov DWORD PTR _a$[ebp+4], 101 ; 00000065H
From the assemble output, memory access through a pointer takes 2 instructions and array only takes 1 instruction.
Why array execute less instructions but it doesn't takes less time than pointer?
Does it associated with the cpu cache? How can I modify my test code to prove it?