RFR: 8370013: Refactor Double.toHexString to eliminate regex and StringBuilder

Joe Darcy darcy at openjdk.org
Mon Oct 20 04:43:07 UTC 2025


On Tue, 14 Oct 2025 23:26:00 GMT, Shaojin Wen <swen at openjdk.org> wrote:

> This PR refactors the Double.toHexString method to improve its performance by eliminating the use of StringBuilder and regex operations. The new implementation uses a direct byte array approach to construct the hex string representation, which avoids the overhead of StringBuilder operations and regex pattern matching.
> 
> Existing tests in `java/lang/Double/ToHexString.java`.

The existing regression tests may be adequate for this refactoring as the high-level algorithm and special cases are similar, but I'll want to take another look before approving this PR. Thanks.

src/java.base/share/classes/java/lang/Double.java line 731:

> 729:                 // This is used to remove trailing zeros from the hex representation
> 730:                 // We limit to 12 because we want to keep at least 1 hex digit (13 total - 12 = 1)
> 731:                 int trailingZeros = Math.min(12, ((Long.numberOfTrailingZeros(signifBits) & 0xFC) >> 2));

Some additional discussion of the computation here would be helpful to casual readers.

I would also be tempted to add

assert 0 <= trailingZeros && trailingZeros <= 12;

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

PR Comment: https://git.openjdk.org/jdk/pull/27811#issuecomment-3420526051
PR Review Comment: https://git.openjdk.org/jdk/pull/27811#discussion_r2443797708


More information about the core-libs-dev mailing list