DEV Community

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

Collapse
 
masternaveenmit profile image
naveenmittal

I didn't get why compiler is storing value temporarily? Am I missing something?

Collapse
 
hamza profile image
Hamza Tamenaoul • Edited

If as an example a = 2, then arr[a++] requires the storage of the old value of a since after evaluating a++, a would be equal to 3, while it needs to access arr[2].

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.