Most efficient way of incrementing: += Or i+1 Or i++ ?
I:
i += 1;II:
i = i + 5;III:
i++;1 & 2 may be the same; but still there exist different styles (I dare say) to increment. What do you think is the most efficient way of incrementing?
i += 1;II:
i = i + 5;III:
i++;1 & 2 may be the same; but still there exist different styles (I dare say) to increment. What do you think is the most efficient way of incrementing?
Member • Dec 22, 2013
Administrator • Dec 22, 2013
You'll have to justify - 'why'? That's the point of this discussion.Aadit KapoorThe third way is the best way for incrementing only by 1.
Member • Dec 22, 2013
Administrator • Dec 22, 2013
Member • Dec 22, 2013
all the methods give same execution time for me 0.015sKaustubh KatdareWell, I think it'd be an experiment worth doing. Anyone wants to take it up?
Administrator • Dec 22, 2013
Interesting. How many decimals can we go down deeper to track time accurately?Vishal0203all the methods give same execution time for me 0.015s
Member • Dec 22, 2013
Member • Dec 22, 2013
Administrator • Dec 22, 2013
Member • Jan 7, 2014
Member • Jan 7, 2014
Member • Jan 7, 2014
Member • Jan 7, 2014
Member • Jan 8, 2014
Member • Jan 9, 2014
for op in "i += 1" "i = i + 1" "i++" "++i"; do echo -e "\nTrying \"$op\"" echo "int f(int i){ $op; return i;}" | gcc -x c -O2 -c -o f.o - objdump -d f.o | tail -n +8 done rm -f f.oI think there is a slight advantage to preincrementing in complex expressions (which would require a more complex test) because the processor can fetch, increment, save and use what's in it's register without any juggling.
Member • Jan 9, 2014
Member • Jan 9, 2014
After i++, if you were to print i, won't it be incremented? So the result have to be assigned to i.Aadit Kapoori++ is the best way to increment by 1 because i++ means only to do +1 whereas i+=1 means first adding +1 to it and then assigning the result to i.So,i++ is more faster than i+=1.
Member • Jan 16, 2014