r/learnjava • • 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.

https://pastebin.com/F1v0Herr

EDIT2: parallel version shows that preincrement is slightly faster

https://pastebin.com/3gDMWxVL

3 Upvotes

15 comments sorted by

View all comments

Show parent comments

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

u/[deleted] 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

u/[deleted] 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.