In C, accessing my array index is faster or accessing by pointer is faster?

前端 未结 8 1027
忘了有多久
忘了有多久 2021-01-04 06:33

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.

8条回答
  •  温柔的废话
    2021-01-04 07:02

    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:

    • There is no absolute answer to your question. You have to try and make measures.
    • If there is a detectable difference (chances are that there will be none), it is hard to predict in which direction, and it depends on a huge set of external factors, including the specific compiler version and optimization flags, processor architecture and model, memory layout and so on.
    • You will not be able to make any reliable optimization gain without having some rather in-depth knowledge of assembly, and a bit of theory of compilation.
    • You should concentrate on making a correct code first, and then only worry about optimization; and there is no performance issue until it has been duly measured in realistic conditions.

提交回复
热议问题