How come my array index is faster than pointer

后端 未结 10 620
青春惊慌失措
青春惊慌失措 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:06

    Oops, on my 64-bit system results are quite different. I've got that this

     int i;
    
     for(i = 0; i < size; i++)
     {
         *(a+i) = 0;
     }
    

    is about 100 times !! slower than this

     int i;
     int * p = a;
    
     for(i = 0; i < size; i++)
     {
         *(p++) = 0;
     }
    

    when compiling with -O3. This hints to me that somehow moving to next address is far easier to achieve for 64-bit cpu, than to calculate destination address from some offset. But i'm not sure.

    EDIT:
    This really has something related with 64-bit architecture because same code with same compile flags doesn't shows any real difference in performance on 32-bit system.

提交回复
热议问题