which is faster assigning a number to the variable or changing the value of that variable either by adding or subtracting some number?

Supposing the modification of a affect the stack rather than a is only supported by a register :

  • a = 11 is a simple write, and on a lot of CPU the CPU executes the next instruction(s) before the write in memory is finished (under condition of memory access(es) of course)

  • a +=1 need first to read the value then when it is done to increment it then to write the new value, all of that even through a single assembler instruction. This needs more time than a write except if the CPU is able to parallelize the read+increment+write with the next instruction(s).

If the use of a optimized to be only supported by a register all depends on the length of the instruction, to increment a register can need less bytes than to set a value and be faster then, mainly when the assigned value is large.

Whatever the case the difference of time is almost nothing, to have a source code readable and robust is more important

  • a = 11 is both readable and robust
  • a += 1 is only right when a already values 10 and this is both less readable (it is needed to look before to guess a will value 11) and less robust (if a change is done before a may not value 10 as expected)

Browse More Popular Posts

Leave a Comment