In C, accessing an array index is faster or accessing by pointer is faster? By faster I mean, which one would take less clock cycle. The array is not an constant array.
When accessing an array through an index, you are actually performing two operations: an addition (adding the index to the base array address), then a memory access (actually reading or writing what is at the resulting address). I suppose that when you are talking about "accessing by pointer" then you mean that you already have the pointer to the target element. So, logically, using the pointer saves the "addition" part, and thus should be faster, or at least no slower.
However...
As a rough approximation, in a modern computer, the memory access is much more expensive than an addition (especially if it falls out of the caches), so the difference, if any, will be slight. On some architectures (e.g. x86 or PowerPC), the addition and memory access can be combined into a single opcode. Things will also be different, depending on whether the array address is a compile-time constant (i.e. the array is not constant data, but is declared as a global variable, vs a block obtained with malloc()
). Using an array may help the compiler find better code, with regards to a generic pointer (in particular when the restrict
keyword is used). The context has a huge influence (e.g. how many free registers there are at that point ?).
So: