为什么ñ++比N = N + 1执行速度更快? [英] Why does n++ execute faster than n=n+1?

查看:182
本文介绍了为什么ñ++比N = N + 1执行速度更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,为什么ñ++ 执行比快N = N + 1

In C language, Why does n++ execute faster than n=n+1?

(int n=...;  n++;)
(int n=...;  n=n+1;)

我们的教练要求在今天的类问题。 (这不是做作业)

Our instructor asked that question in today's class. (this is not homework)

推荐答案

如果您是在的石器时代的编译器...

That would be true if you are working on a "stone-age" compiler...

石器时代的情况下:结果
++ñ高N ++ 快于 N = N + 1

机通常有增加x 以及添加一个const,以X

In case of "stone-age":
++n is faster than n++ is faster than n=n+1
Machine usually have increment x as well as add const to x


  • 的情况下,N + ,你将有2个内存访问只(读N,INC N,写N)

  • 的情况下,N = N + 1 ,你将有3内存访问(读取n,读常量,添加n和常量,写N)

  • In case of n++, you will have 2 memory access only (read n, inc n, write n )
  • In case of n=n+1, you will have 3 memory access (read n, read const, add n and const, write n)

但是,今天的编译器会自动转换 N = N + 1 ++ñ,它会做更多比你可以想象!

But today's compiler will automatically convert n=n+1 to ++n, and it will do more than you may imagine!!

同样在今天的乱序处理器-despite的的石器时代的反编译运行时可能不会受到影响的所有在许多情况下的情况下!

Also on today's out-of-order processors -despite the case of "stone-age" compiler- runtime may not be affected at all in many cases!!

<一个href=\"http://stackoverflow.com/questions/2823043/is-it-faster-to-count-down-than-it-is-to-count-up/2823095#2823095\">Related

这篇关于为什么ñ++比N = N + 1执行速度更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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