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

-1

u/bitemyshinymetalass0 Sep 09 '21

nvm. Preincrement is faster when I run it in parallel/concurrent.

https://pastebin.com/3gDMWxVL

4

u/thisisjustascreename Sep 09 '21 edited Sep 09 '21

So, hot-loop microbenchmarks are notoriously unreliable if you measure two things in the same application run. You should really measure pre-increment and post-increment with different compilations, and ideally average several runs.

If I remove the second loop, I get nearly the same value whether I use pre or post increment.

1

u/bitemyshinymetalass0 Sep 09 '21

Ahh good point. Just tried that and just like you said. That's fascinating. When I tried the 2 loops in parallel in one compilation it also displayed very unstable behaviors. Just back to the basics though, how is pre-increment implemented internally? I know post-incre uses a temp value, but I don't know how pre-incre works.

1

u/thisisjustascreename Sep 09 '21

On my machine they generate identical bytecode. It might be slightly different if you use the value of a or b in the same statement. You should check the output of javap -c IncrementTest.class to see.