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

前端 未结 8 1056
忘了有多久
忘了有多久 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 06:47

    At the lowest level, these operations mostly tend to compile to the same thing. If you're really interested, you should get your C compiler to generate assembly output (such as with gcc -S) so you can check, especially since it depends, at a bare minimum, on:

    • your target platform.
    • your compiler.
    • your optimisation level.

    You'll find that, even if there was a difference (which is doubtful), that level of micro-optimisation is mostly not worth the effort you put into it. You're better off doing macro-optimisations such as improved algorithms since that's the sort of thing that offers more return on investment.

    In these sorts of situations, where the effect is likely to be minimal, I always optimise for readability.

提交回复
热议问题