In my program an array is accessed millions of times. Is it faster to access the contents of the array by dereferencing the pointer like this, *(arr + i), instead of using square brackets?
Asked
Active
Viewed 949 times
0
-
It really depends on which machine you are using. AS400 has 32 byte (not bit) pointers. Are you using AS400? – cup Oct 30 '18 at 04:22
-
4`*(arr+i)` *is* `arr[i]` ... (for an array, as specified in the question, thus not a duplicate of array vs pointer) – Déjà vu Oct 30 '18 at 04:46
-
1This is not a duplicate of array vs pointer. – R.. GitHub STOP HELPING ICE Oct 30 '18 at 09:36
-
1Hello @Double_O_Seven, welcome to Stack Overflow You can check the difference using: https://godbolt.org/ – José Manuel Ramos Oct 30 '18 at 09:44
-
@JoséManuelRamos: That's a great piece of advice but slightly imprecise. Godbolt is great for showing you what particular compilers do, but it can't tell you they're formally equivalent as well. – R.. GitHub STOP HELPING ICE Oct 30 '18 at 15:03
-
Indeed, theory and practice could be different. That's why one of the greatests mistakes/advantages of C is the equivalence between `*a`, `*(a + 0)` and `a[0]`. Demonstrating this with the assembly equivalent of a basic code involves this trick helps to solve this question. – José Manuel Ramos Oct 30 '18 at 15:15
-
2There is effectively no difference in performance between the two (they *should* result in identical machine code). The question you *should* be asking is, "which is easier to read and understand," or "which am I less likely to make a mistake with." The answer to both is to use bracket notation, `arr[i]`. – John Bode Oct 30 '18 at 15:39
2 Answers
8
As Ring Ø noted in a comment, they are identical by definition; if there is any difference in how they perform, it's nothing but intentional badness on the part of the compiler.

R.. GitHub STOP HELPING ICE
- 208,859
- 35
- 376
- 711
-
What about `ptr + offset` vs `&ptr[offset]`? They also should be exactly the same, but the latter, at least if you go step by step, does more and is redundant, does compiler also optimize this? – Purple Ice Oct 30 '18 at 12:16
-
3@PurpleIce: They do mean exactly the same thing. According to the standard, `&*` is a no-op. ("If the operand [of the `&` operator] is the result of a unary `*` operator, neither that operator nor the `&` operator is evaluated and the result is as if both were omitted..." [6.5.3.2/3](https://port70.net/~nsz/c/c11/n1570.html#6.5.3.2p3)) – rici Oct 30 '18 at 14:53
1
*(arr+i)
is the equivalent of arr[i]
. A compiler would be expected to emit the same code.
As with such style issues, code to your group's coding guidelines, which I expect to be arr[i]
.
With no guidelines, code for clarity. @John Bode

chux - Reinstate Monica
- 143,097
- 13
- 135
- 256