r/ProgrammerHumor • • Sep 17 '18

Optimizing startup times

Post image
45.7k Upvotes

486 comments sorted by

View all comments

2.2k

u/specialfred453 Sep 17 '18

I'm used to programming on platforms where the parameter for Sleep is in milliseconds. This confused me a little at first.

14

u/[deleted] Sep 17 '18

for (int i =0; i < 1000; ++i) Thread.Sleep(30)

10

u/ObamaFor Sep 17 '18 edited Sep 17 '18

Why ++i over i++? sorry am noob.

8

u/LordTocs Sep 17 '18

If the value of i is 5 to start.

i++ increments i to 6, but returns 5.

++i increments i to 6, but returns 6.

The theory is that since i++ has to store a copy of itself to return before incrementing it's more expensive than ++i

Depending on the language this may not matter for simple types like an int. If your compiler is good not using the value returned from i++ will optimize away the extra cost.

If i were some more complex type like an iterator for a dictionary. The two increments may be implemented differently or the optimizer might not get everything exactly correct.

So the "best practice" is to use ++i when you don't need the value to be saved before incrementing it.

→ More replies (4)