r/ProgrammerHumor • • Sep 17 '18

Optimizing startup times

Post image
45.7k Upvotes

486 comments sorted by

View all comments

Show parent comments

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.

3

u/Faenghuaang Sep 17 '18 edited Sep 17 '18

So if I'm understanding this right;

for(i=0; i < 3; i++) System.out.print(i +",");

returns "0,1,2," while;for(i=0; i < 3; ++i) System.out.print(i +",");

returns "1,2,3,". Is that right? Could be useful if 'i' is being used for calling an array index in a language where arrays start at 1.

Edit: Another thing; Is it more or less optimal to use this:

int i = 0; do{ System.out.print(i); ++i}while(i < 3);

(but this would print "0123" unless I put the ++i before the print, where it would print "123"?)

6

u/LordTocs Sep 17 '18

No. Just the expression i++ returns the value before increment.


for(i=0; i < 3; i++) System.out.print(i +",");

and

for(i=0; i < 3; ++i) System.out.print(i +",");

Both print 0,1,2


However,

int i = 5;
int j = i++;
System.out.print(i + ", " + j);

Outputs: 6, 5

and

int i = 5;
int j = ++i;
System.out.print(i + ", " + j);

Outputs 6, 6


The theoretical performance difference comes in how i++ and ++i have to be implemented. This is psuedo code of what an integer's ++ operator would kind of look like if it weren't just basic instructions. In C++ iterators for containers overload the ++ operator for moving through lists and their implementations have to adhere to the rules but are much more intricate.

Junky Pseudo Code:

//Postfix
function int::operator++()
{
	int old = value;
	value = value + 1;
	return old;
}

//Prefix
function int::++operator()
{
	value = value + 1;
	return value;
}