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?
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?
Array indexing has a cleaner syntax
You said it yourself! So why bother and make your life difficult. When you come back later to your code it will be more easy to understand then if you used pointer arithmetic. If you have a good C++ compiler he would translate both options the same way!
Alright, thanks! :)
>but (as I've read) pointer arithmetic is faster
Prove it. In your example, the two are quite likely compiled to exactly the same machine code. Array subscripting is literally syntactic sugar for the equivalent pointer offset calculation. A more likely example is this:
int x[N];
int *p = x;
for ( int i = 0; i < N; i++ )
process ( x[i] );
for ( int i = 0; i < N; p += i )
process ( *p );
The latter could very well be faster (though I would question why you're worried about such micro-optimizations) due to the fact that the body of the loop is only performing a dereference rather than an addition and a dereference.
My advice is not to worry about it. Use whichever more clearly displays your intentions.
From the C++ Standard:
The expression E1[E2] is identical (by definition) to *((E1)+(E2)).
Sometime pointer arithmetics code is evidently cleaner than "subsripted" one:
int countDigits(const char* str)
{
int n = 0;
if (str)
while (int c = *str++)
if (c >= '0' && c <= '9')
++n;
return n;
}
Sometimes we have no choice: as usually (but not always) pointer arithmetics code is faster than "subscripted" one on embedded systems where we (often) must save on every microsecond...
It's a far-fetched problem. It's not a language problem...