0

Some C book author says that accessing an array value through the pointer is faster than through array indexing. But is this true? Here are two programs that I have written to understand the concept.

main()
{
    int arr[100000],*ptr,c,i;
    ptr=arr;
    for(i=0;i<100000;i++)
      arr[i]=i;
    for(i=0;i<100000;i++)
      c = arr[i];
}

main()
{
    int arr[100000],*ptr,c,i;
    ptr=arr;
    for(i=0;i<100000;i++)
      *(ptr+i)=i;
    for(i=0;i<100000;i++)
      c = *(ptr+i);
}

When I run these two with time ./a.out the second program takes more time. This means the use of pointers takes more time than the array index method. Could you please explain to me how this works, with these simple programs?

MrHug
  • 1,315
  • 10
  • 27
Akash Patel
  • 27
  • 1
  • 8
  • That isn't what they meant by pointer-accessing. And regarding the timing, there are so several items you didn't bother mentioning you accounted for (debug vs release, decompiled asm analysis ). If benchmarking were as simple as a `time` process monitor we'd all be overpaid statisticians. – WhozCraig Oct 08 '14 at 07:41
  • I think you meant this: http://stackoverflow.com/q/26241007/2455888 – haccks Oct 08 '14 at 07:45
  • Add the '`-g`' flag when compiling with `gcc`.`objdump -D a.out > file`, for both the programs. Remember to create two different files for each program. Now do vimdiff file1 file2. Compare the difference, however I think there won't be any difference. – Raunak Mukhia Oct 08 '14 at 07:46

2 Answers2

2

Your "pointer-accessing" is not the intended, faster, way.

You're just doing the same thing as the indexing, remember that in C the expression

A[i]

is equivalent to

*(A + i)

So, your second loop is just expressing array indexing manually, which is pointless.

It should be:

int main(void)
{
    int arr[100000], *ptr, *end, c;
    for(ptr = arr, end = arr + sizeof arr / sizeof *arr, i = 0;
        ptr != end; ++i)
    {
      *ptr++ = i;
    }
    for(ptr = arr; ptr != end; )
      c = *ptr++;
    return 0;
}

Or something. Still no guarantee that this is faster, but at least it tries to do fewer operations.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 1
    +1 high confidence this is more in tune with what the pointers-are-faster claim was intending. – WhozCraig Oct 08 '14 at 07:48
  • This has a good chance of saving a register, which is good for machines like x86, but not all that critical on x86-64 or similar. – EOF Oct 08 '14 at 08:31
0

This is the same. Operator [] just adds index to array begin.

noktigula
  • 425
  • 6
  • 15