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?
Join CrazyEngineers to reply, ask questions, and participate in conversations.
CrazyEngineers powered by Jatra Community Platform
@aadit-kapoor-EBxnXT • Dec 22, 2013
@thebigk • 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.
@anoop-kumar-GDGRCn • Dec 22, 2013
@thebigk • Dec 22, 2013
@vishal-pysGmK • 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?
@thebigk • 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
@anand-tamariya-DnfjEX • Dec 22, 2013
@abhishek-fg9tRh • Dec 22, 2013
@thebigk • Dec 22, 2013
@maro-Ce3knx • Jan 7, 2014
@ahmed-Dx1LlC • Jan 7, 2014
@kenjackson-mBf7HF • Jan 7, 2014
@anand-tamariya-DnfjEX • Jan 7, 2014
@ahmed-Dx1LlC • Jan 8, 2014
@kenjackson-mBf7HF • 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.
@aadit-kapoor-EBxnXT • Jan 9, 2014
@anand-tamariya-DnfjEX • 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.
@sookie-T06sFW • Jan 16, 2014