RFR: 8315585: Optimization for decimal to string

Shaojin Wen swen at openjdk.org
Tue Jan 28 08:12:29 UTC 2025


On Sun, 26 Jan 2025 19:31:08 GMT, Johannes Graham <duke at openjdk.org> wrote:

>> Continue to complete PR #16006 and PR #21593 to improve BigDecimal::toString and BigDecimal::toPlainString performance and reduce duplicate code
>
> src/java.base/share/classes/java/math/BigDecimal.java line 3538:
> 
>> 3536:             return (signum < 0 ? "-0." : "0.").concat(intString);
>> 3537:         } else if (insertionPoint > 0) { /* Point goes inside intVal */
>> 3538:             buf = new StringBuilder();
> 
> Could calculate the precise size for the StringBuilder

The performance will degrade if you precompute the length of the StringBuilder.

> src/java.base/share/classes/java/math/BigDecimal.java line 3542:
> 
>> 3540:                 buf.append('-');
>> 3541:             buf.append(intString)
>> 3542:                     .insert(insertionPoint + (signum < 0 ? 1 : 0), '.');
> 
> Instead of the insert, could do an append of the  prefix, then dot, then the suffix.

buf.append(intString, 0, insertionPoint)
   .append('.')
   .append(intString, insertionPoint, intString.length());


This is another way to write it, but the performance will be reduced.

> src/java.base/share/classes/jdk/internal/util/DecimalDigits.java line 347:
> 
>> 345:      * @return index of the most significant digit or minus sign, if present
>> 346:      */
>> 347:     public static int getChars(long i, int index, char[] buf) {
> 
> Before dropping this method, there is another candidate to use  it here : https://github.com/openjdk/jdk/blob/1d2eb2fbaea700fc77b644b5eb5a8a7c40ede108/src/java.base/share/classes/jdk/internal/math/FloatingDecimal.java#L367

I took a look at the FloatingDecimal related code. The relevant code in FloatingDecimal can be refactored and simplified so that the removed code does not need to be used.

I submitted a PR to simplify FloatingDecimal https://github.com/openjdk/jdk/pull/23311

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

PR Review Comment: https://git.openjdk.org/jdk/pull/23310#discussion_r1930019634
PR Review Comment: https://git.openjdk.org/jdk/pull/23310#discussion_r1930024839
PR Review Comment: https://git.openjdk.org/jdk/pull/23310#discussion_r1929539931


More information about the core-libs-dev mailing list