[C++]array indexing vs pointer arithmetic

Started by
4 comments, last by Antheus 15 years, 5 months ago

int x[5];
x[4] = 10;
*(x + 4) = 10;

Array indexing has a cleaner syntax but (as I've read) pointer arithmetic is faster. My question is, is it worth to use pointer arithmetic? Is there a noticeable difference?
Advertisement
AFAIK, they are pretty much the same thing, there's no difference. But if you want to be sure about that, look at the disassembly of both and compare them.
.
It isn't faster.

Lets imagine you are writing a compiler. Since the two operations are equivalent, why wouldn't you make them compile to the same assembly?

The only place I use pointer arithmetic is when I am using pointers as iterators. E.g:
int x[5];for(int *ptr = x ; ptr != x + 5 ; ++ptr){   // ...}

Even then, this kind of code is usually wrapper in std::for_each, std::find or std::copy (and so on...).
In the general case, pointers are slower due to aliasing considerations that prevent optimization.

Note that a is identical to *(a+i) by definition, so neither is faster.
Quote:Original post by sheep19
Array indexing has a cleaner syntax but (as I've read) pointer arithmetic is faster.

Where did you read this?

a is only syntactic sugar for *(a+i), that is, the "array indexing operator" as we call it isn't even defined for arrays, only for pointers. In the expression a+i, the array name a decays into a pointer to its first element, then we add i to get to the i-th position, and then we dereference that new pointer to get the element at that position.

If you compile your program with gcc -S and look at the generated assembly, you will notice that a and *(a+i) compile to the exact same code. There is absolutely no difference.
Quote:Original post by ToohrVyk
In the general case, pointers are slower due to aliasing considerations that prevent optimization.


This is general recommendation (see 2.2 (pdf)). In practice, there really is no difference, or it is completely compiler dependent.

This topic is closed to new replies.

Advertisement