In general,the process of indexing an array takes more time to execute than does
the process of accessing the contents of a pointer. In fact,this is one of the main reasons
why pointers are used to access the elements of an array—the code that is generated is
generally more efficient. Of course,if access to the array is not generally sequential,
pointers accomplish nothing,as far as this issue is concerned,because the expression
*(pointer + j) takes just as long to execute as does the expression array[j].
有人可以解释什么比什么更快?具体来说,如果array [j]的速度= *(指针j)的速度那么索引数组的过程是什么,以及访问指针内容的过程是什么?此外,有关SO的问题和答案提到在编译期间将数组[j]转换为*(数组j),因此不应有任何区别.
解决方法
int arr[5] = {0}; int *p = arr; int c = 1;
现在,看到循环1:
for(int i = 0; i < 5; i++) arr[i] = c++ + 1;
循环2:
for(int i = 0; i < 5; i++) *p++ = c++ + 1;
这两个循环之间的区别在于它们的身体.第一个循环包含arr [i] = c 1.这相当于*(arr i)= c 1. *(arr i)是什么意思?
这意味着:
>获取基指针地址.
>获取i的值
>将i的值添加到基址.
>取消引用最终地址.
在第二个循环的主体* p的情况下,意味着:
当然第二个会执行得更快.但是,现在有一天现代编译器足够智能来优化这些代码,并且很可能你会得到两个循环相同的结果.