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?

3
  • 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. Commented Oct 8, 2014 at 7:41
  • I think you meant this: stackoverflow.com/q/26241007/2455888 Commented Oct 8, 2014 at 7: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. Commented Oct 8, 2014 at 7:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 high confidence this is more in tune with what the pointers-are-faster claim was intending.
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.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.