RFR: 8355719: Reduce memory consumption of BigInteger.pow() [v51]

Raffaello Giulietti rgiulietti at openjdk.org
Wed May 7 17:39:20 UTC 2025


On Wed, 7 May 2025 17:14:19 GMT, fabioromano1 <duke at openjdk.org> wrote:

>> src/java.base/share/classes/java/math/BigInteger.java line 2643:
>> 
>>> 2641:                     : new BigInteger(result, newSign).shiftLeft(bitsToShift);
>>> 2642:         } else {
>>> 2643:             if ((bitLength() - 1L) * exponent >= (long) MAX_MAG_LENGTH << 5) {
>> 
>> Suggestion:
>> 
>>             if ((bitLength() - 1L) * exponent >= 32L * MAX_MAG_LENGTH) {
>> 
>> or
>> Suggestion:
>> 
>>             if ((bitLength() - 1L) * exponent >= (long) Integer.SIZE * MAX_MAG_LENGTH) {
>> 
>> 
>> Both variant are easier to read, more honest, and exactly as efficient as with the shift. The right-hand sides are compile-time constants, so they have no impact on runtime performance.
>> 
>> More generally, the runtime compilers are perfectly capable to optimize multiplications by constant powers of 2 and replace them with shifts, even if the other operand is not a constant.
>
> @rgiulietti What about `(bitLength() - 1L) * exponent >= Integer.MAX_VALUE`?

Ah right, but you probably want
Suggestion:

            if ((bitLength() - 1L) * exponent > Integer.MAX_VALUE) {

I mean `>` rather than `>=`

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/24690#discussion_r2078138621


More information about the core-libs-dev mailing list