DEV Community

Discussion on: Why some think ++i is faster than i++ ?

Collapse
 
merri profile image
Vesa Piittinen • Edited

I have not studied compilers, but this is what I think is the difference:

arr[i++]

  1. Compiler finds i
  2. Compiler finds ++ which will increment i
  3. Compiler needs original value of i to access arr, so it makes a temporary clone before increment
  4. Compiler increments i
  5. Compiler accesses arr with value of temporary clone

Value of i cannot be used directly because it has been mutated, so a clone with previous value is required.

arr[++i]

  1. Compiler finds ++ which will increment i
  2. Compiler increments i
  3. Compiler accesses arr with value of i

Value of i can be used directly.