r/learnjava • u/bitemyshinymetalass0 • Sep 09 '21
++x vs x++ speed
Why is x++ so much faster than ++x in Java? I tested with a loop that adds all positive numbers in Integer for Integer.MAX_VALUE times. x++ is always twice as fast. How are they different under the hood? Is that the case in other languages?
EDIT: here is the code. Might have to use -Xmx tag if more loop times is desired.
EDIT2: parallel version shows that preincrement is slightly faster
1
u/jacob_scooter Sep 10 '21
x++ adds one to x after the current operation
++x adds one before the current operation
there shouldn’t be a speed difference
1
u/fredoverflow Sep 11 '21
If you ignore their result, ++x; and x++; compile to the exact same Java bytecode iinc x, 1: https://www.youtube.com/watch?v=bONciSOJ_N4&t=95
1
-1
Sep 09 '21
Well. That's not the point..try doing this with both pre and both post.
0
u/bitemyshinymetalass0 Sep 09 '21
What do you mean both pre and both post? My goal was to compare speed between pre and post.
-4
Sep 09 '21
Compare speed between both pre and post
1
u/bitemyshinymetalass0 Sep 09 '21
You mean run them in parallel? I just tried and pre is faster as expected. So I guess maybe there's some runtime or compiler optimization happening since the loops are the same.
-10
Sep 09 '21
Omg just do both pre or both post. a++ with b++ or ++a and ++b
3
u/bitemyshinymetalass0 Sep 09 '21
Wait what. Maybe I'm dumb beyond saving but what's the point in that? I don't need to run it twice for each type of syntax I'm comparing.
2
u/thisisjustascreename Sep 09 '21
It shouldn't be, can you share your code?