How come my array index is faster than pointer

后端 未结 10 626
青春惊慌失措
青春惊慌失措 2020-12-17 16:58

Why the array index is faster than pointer? Isn\'t pointer supposed to be faster than array index?

** i used time.h clock_t to tested two functions, each loop 2 mil

10条回答
  •  青春惊慌失措
    2020-12-17 17:15

    Array dereference p[i] is *(p + i). Compilers make use of instructions that do math + dereference in 1 or 2 cycles (e.g. x86 LEA instruction) to optimize for speed.

    With the pointer loop, it splits the access and offset into to separate parts and the compiler cannot optimize it.

提交回复
热议问题