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

前端 未结 8 1054
忘了有多久
忘了有多久 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:45

    It's completely system-dependent which one is faster, but the two are functionally equivalent to one another and I'd be really surprised if one actually was faster. That is, the code

    myArr[index]
    

    Is completely equivalent to

    *(&myArr[0] + index)
    

    Similarly, writing

    *ptr
    

    Is equivalent to writing

    ptr[0]
    

    Most compilers are smart enough to figure this out, so I'd be amazed if one was faster than another.

    More importantly, though, you probably shouldn't be too worried about this. Worry about optimizations after you have everything else working. If you find that array accesses really are killing you, then consider finding a faster alternative. Otherwise, don't worry about it; it's infinitely more valuable to have clean, readable, maintainable code than it is to have optimized code unless you have a pressing need for optimization.

提交回复
热议问题