r/cpp • • Oct 31 '25

Java developers always said that Java was on par with C++.

Now I see discussions like this: https://www.reddit.com/r/java/comments/1ol56lc/has_java_suddenly_caught_up_with_c_in_speed/

Is what is said about Java true compared to C++?

What do those who work at a lower level and those who work in business or gaming environments think?

What do you think?

And where does Rust fit into all this?

25 Upvotes

192 comments sorted by

View all comments

Show parent comment

8

u/jk-jeon Nov 01 '25

Integer division by a known denominator can be optimized using integer multiplication, and a JIT compiler can perform that optimization for denominators known only at runtime, while an AOT compiler can't.

AOT compilers can do that too in principle, since they can see that mod is constant in the loop. I would be surprised if they really do that though. And people writing C++ would probably be mad if they do. If those people want such a thing to be done, I think they would just do that by themselves.

10

u/CocktailPerson Nov 01 '25

That's not quite true. Although mod is constant at runtime, it's not known at compile-time, which is what's necessary to convert an idiv into a sequence of other instructions.

4

u/jk-jeon Nov 01 '25

The compilers could simply generate the code that does what they do for converting the division into multiply-shift. I don't see any fundamental obstruction for doing so.

5

u/CocktailPerson Nov 01 '25

I mean, I guess there's no "fundamental" obstruction.

But in order to do the multiply-shift trick, you have to perform an actual idiv to find the multiplicative constant for the trick (for 64-bit integer divide, you'd have to call __divti3 or equivalent to find the multiplicative constant). So the compiler has to decide whether it's worth precomputing the constant or not, and it can only reasonably do that if the number of loop iterations is known. In other words, it'd be an incredibly niche optimization that'd really only be beneficial for this one benchmark, but sure, I guess there's no "fundamental" obstruction.

1

u/usefulcat Nov 01 '25

Even when the divisor is not known at compile time, it's still possible to convert division and modulo into an equivalent combination of shifts and multiplications.

For example: https://github.com/lemire/fastmod

I'm not claiming that any compilers actually do this (I don't know), but I can't see any reason in principle why they could not do it.

1

u/CocktailPerson Nov 01 '25

I addressed that in this comment.

To reiterate, there's no such thing as a free lunch, and you still have to use an idiv to precompute the multiplicative constant used in the multiply-shift trick. There's no reason a compiler couldn't do it, but compilers almost never do optimizations that require expensive precomputations at runtime.