C和C ++:数组元素访问指针VS INT [英] C and C++: Array element access pointer vs int

查看:201
本文介绍了C和C ++:数组元素访问指针VS INT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有性能上的差异,如果你不是做 myArray的[我] 或存放 myarray中的ADRESS [I] 在一个指针?

Is there a performance difference if you either do myarray[ i ] or store the adress of myarray[ i ] in a pointer?

编辑:的指针都在我的程序中一个不重要的步骤,其中表现为无标准计算。在关键部位的指针保持静态和不会被修改。现在的问题是,如果这些静态指针比使用 myArray的[我] 所有的时间更快。

The pointers are all calculated during an unimportant step in my program where performance is no criteria. During the critical parts the pointers remain static and are not modified. Now the question is if these static pointers are faster than using myarray[ i ] all the time.

推荐答案

有关此code:

int main() {
    int a[100], b[100];
    int * p = b;
    for ( unsigned int i = 0; i < 100; i++ ) {
        a[i] = i;
        *p++ = i;
    }
    return a[1] + b[2]; 
}

在与以g -O3优化++,语句建:

when built with -O3 optimisation in g++, the statement:

a[i] = i;

生成的汇编输出:

produced the assembly output:

mov    %eax,(%ecx,%eax,4)

和下面的语句:

*p++ = i;

生产的:

mov    %eax,(%edx,%eax,4)

因此​​,在这种情况下,有在两者之间没有差别。然而,这是不是也不可能是一般规则 - 优化器很可能会产生完全不同的code甚至略有不同的输入

So in this case there was no difference between the two. However, this is not and cannot be a general rule - the optimiser might well generate completely different code for even a slightly different input.

这篇关于C和C ++:数组元素访问指针VS INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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