Why does n++ execute faster than n=n+1?

That would be true if you are working on a “stone-age” compiler…

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

  • 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)

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

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!!

Related

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)