为什么在循环使用数组索引数组比指针访问慢? [英] Why looping over array using array indexing is slower than that of pointer access?

查看:145
本文介绍了为什么在循环使用数组索引数组比指针访问慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读科昌的书,在C程序设计。在部分指针和P阵列。 264,他说:

I'm reading Kochan's book "Programming in C". In section Pointer and Arrays on p. 264 he says:

在一般情况下,索引的阵列的过程中需要更多的时间比不执行
  访问指针的内容的过程。事实上,这是主要的原因之一
  为什么指针被用来访问的阵列的$ C $所生成是c的元素
  通常更有效。当然,如果访问阵列一般不是连续的,
  指针一事无成,就这个问题而言,由于前pression
  *(指针+ J),只需只要执行一样的前pression阵列[J]。

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].

有人能解释一下什么是比快?特别是,如果阵列[J] = *的速度(指针+ J)的速度又是什么的索引数组的过程的是什么的访问指针的内容<过程/ em>的?此外,还有上,这样提的是阵列[J]编译过程中被转换为*(阵列+ J),所以不应该有任何区别的问题和答案。

Can someone explain what is faster than what ? Specifically, if speed of array[j] = speed of *(pointer + j) then what is the process of indexing an array and what is the process of accessing the contents of a pointer ? Also, there are questions and answers on SO that mention that array[j] is converted to *(array+j) during compilation so there shouldn't be any difference.

摘要:
请给我什么科昌说,一个很简单的例子。 2件code和点以更快之一,没有解释为什么它是真实的。

Summary: Please give me a very simple example of what Kochan says. 2 pieces of code and point at faster one, don't have to explain why it is true.

推荐答案

看段

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; 

这两个环路之间的差别是他们的身体。第一循环包含改编[i] = C ++ + 1 。这等同于 *(ARR + I)= C ++ + 1 。这是什么意思 *(ARR + I)?结果
这意味着:

The difference between these two loops is their body. First loop contains arr[i] = c++ + 1. This is equivalent to *(arr + i) = c++ + 1. What does it mean by *(arr + i)?
It means that:


  • 获得基本指针地址。

  • 取值​​ I

  • I 的值加到基址。

  • 取消引用的最终地址。

  • Fetch the base pointer address.
  • Fetch the value of i
  • Add the value of i to the base address.
  • Dereference the final address.

而在第二循环体的情况下, * P ++ 意思是:

While in case of second loop's body *p++ means:


  • 取值​​ P

  • 取消引用递增之前的地址。

  • 增量为 1 的地址。

  • Fetch the value of p
  • Dereference the address before incrementing it.
  • Increment the address by 1.

当然,第二个会执行得更快。但是,现在是一个天现代编译器有足够的智慧来优化这些codeS并极有可能你会得到两个循环相同的结果。

Of course second one will execute faster. But, now a days modern compilers are smart enough to optimize these codes and most probably you will get the same result for both loop.

这篇关于为什么在循环使用数组索引数组比指针访问慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆