In C, subscripting (e.g., arr[i][j]) and pointer arithmetic (e.g., *(*(arr + i) + j)) for array access are effectively equivalent in terms of performance, especially for optimized code. Under the hood, the compiler typically generates the same machine code for accessing an array whether you use subscripts or pointer arithmetic.
In an unoptimized build, pointer arithmetic could potentially result in slightly slower code because the compiler might perform the arithmetic operations explicitly. However, when optimizations are enabled (e.g., using the -O2 or -O3 compiler flags), the compiler is likely to optimize away the difference, resulting in identical performance.
To summarize:
- Subscripting (
arr[i][j]) is often more readable and convenient, especially for multidimensional arrays, because it matches the array declaration structure.
- Pointer arithmetic (
*(*(arr + i) + j)) offers more flexibility and can make some operations more explicit, which might be needed in lower-level programming or for certain algorithms.
A modern C compiler will typically optimize both access methods to the same set of operations at the assembly level, making their performance equivalent in most cases. It's always a good idea to profile your code with optimizations turned on before making judgments about performance differences.
If performance is critical, use compiler optimizations and profile your code. In practice, other factors such as cache locality, memory access patterns, and overall algorithmic efficiency often have a much bigger impact on performance than the choice between pointers and subscripts for array access.