哪个赋值运算符更快? [英] which assignment operator is faster ?

查看:109
本文介绍了哪个赋值运算符更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
  int *z = new int[100];
  z[1]=1;
  z[2]=4;
  z[3]=5;
  ...
  z[100]=20;
}


在上面的代码中,分配顺序是从z [0]到z [100],
如果我如下更改顺序,它会变慢吗?


in the above code, the assignment sequence is from z[0] to z[100],
if I change the order as below,will it become slow

{
  int *z = new int[100];
  z[10]=4;
  z[3]=5;
  z[100]=20;
  ...
  z[2]=4;
}

推荐答案

内存操作是在 nano 微秒范围内执行的,因此索引的顺序没有区别
Memory operations are executed in the sub nano micro second range, so the order of the indexing makes no difference to your program.


执行分配的顺序会影响处理器缓存的性能.这可能就是为什么变体1比变体2运行更快的原因.但是,只有多次执行该代码,这才有意义.在当今的处理器上,一百个整数赋值仅花费非常少的时间.
The sequence in which you execute the assignments influences the performance of the processor cache. That''s probably the reason why variant 1 is working faster than variant 2. That should however only be significant if you execute that code many times. A hundred integer assignments just take a very tiny fraction of time by themselves on today''s processors.


顺便说一句...如果您生成像您这样的动态数组:
By the way... if you generate a dynamic array like yours:
int *z = new int[100];


有效索引的范围是0-99,而不是1-100(数组索引是从零开始的).


The valid indexes are from 0-99, not from 1-100 (array indexes are zero based).

z[100] = 20; //out of bounds, likely crash
z[99] = 20; //last valid index


这篇关于哪个赋值运算符更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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