[jdk8u-dev] RFR: 8299677: Formatter.format might take a long time to format an integer or floating-point
Aleksey Shipilev
shade at openjdk.org
Tue Feb 27 18:24:55 UTC 2024
On Mon, 26 Feb 2024 21:54:16 GMT, Chad Rakoczy <duke at openjdk.org> wrote:
> Backport of [JDK-8299677](https://bugs.openjdk.org/browse/JDK-8299677)
>
> Backport was not clean. Rewrote test to not include junit `ParameterizedTest`. Rewrote fix since `String.repeat` is not in JDK8
jdk/src/share/classes/java/util/Formatter.java line 4384:
> 4382: len = sb.length();
> 4383: if (width > len && f.contains(Flags.ZERO_PAD)) {
> 4384: String zeros = new String(new char[width - len]).replace("\0", "0");
In the original patch, we use the locale-dependent `zero` variable here. I don't think we can just use `0`, although I struggle to imagine the case where that would matter. Plus, given we are changing char->char, we can use `String.replace(char,char)` instead of `String.replace(CharSequence,CharSequence)`.
I think we can hit these two birds with one stone by doing:
char[] zeros = new char[width - len];
Arrays.fill(zeros, zero);
sb.insert(begin, new String(zeros));
It is still awkward because `String` constructor copies the array. For extreme use cases, there is a package-private `String(char[] array, boolean share)` constructor that might be accessible through `SharedSecrets.getJavaLangAccess().newSharedString(...)` (needs a new method). But that might be moot point since `AbstractStringBuilder.insert` already does a lot of copies.
-------------
PR Review Comment: https://git.openjdk.org/jdk8u-dev/pull/459#discussion_r1504737711
More information about the jdk8u-dev
mailing list