From 92dfa1175e4898fc491115e004380780b6862473 Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Tue, 21 Feb 2023 13:31:15 +0000 Subject: [PATCH] 8302863: Speed up String::encodeASCII using countPositives Reviewed-by: alanb --- .../share/classes/java/lang/String.java | 35 ++++++++++++------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/src/java.base/share/classes/java/lang/String.java b/src/java.base/share/classes/java/lang/String.java index 1b5b5efb72b..55bbecaf425 100644 --- a/src/java.base/share/classes/java/lang/String.java +++ b/src/java.base/share/classes/java/lang/String.java @@ -874,7 +874,7 @@ public final class String if (coder == LATIN1 && ae.isASCIICompatible() && !StringCoding.hasNegatives(val, 0, val.length)) { - return Arrays.copyOf(val, val.length); + return val.clone(); } byte[] ba = new byte[en]; if (len == 0) { @@ -973,11 +973,10 @@ public final class String private static byte[] encodeASCII(byte coder, byte[] val) { if (coder == LATIN1) { - byte[] dst = Arrays.copyOf(val, val.length); - for (int i = 0; i < dst.length; i++) { - if (dst[i] < 0) { - dst[i] = '?'; - } + int positives = StringCoding.countPositives(val, 0, val.length); + byte[] dst = val.clone(); + if (positives < dst.length) { + replaceNegatives(dst, positives); } return dst; } @@ -1002,13 +1001,21 @@ public final class String return Arrays.copyOf(dst, dp); } + private static void replaceNegatives(byte[] val, int fromIndex) { + for (int i = fromIndex; i < val.length; i++) { + if (val[i] < 0) { + val[i] = '?'; + } + } + } + private static byte[] encode8859_1(byte coder, byte[] val) { return encode8859_1(coder, val, true); } private static byte[] encode8859_1(byte coder, byte[] val, boolean doReplace) { if (coder == LATIN1) { - return Arrays.copyOf(val, val.length); + return val.clone(); } int len = val.length >> 1; byte[] dst = new byte[len]; @@ -1262,8 +1269,7 @@ public final class String } private static void throwMalformed(byte[] val) { - int dp = 0; - while (dp < val.length && val[dp] >=0) { dp++; } + int dp = StringCoding.countPositives(val, 0, val.length); throwMalformed(dp, 1); } @@ -1278,11 +1284,13 @@ public final class String } private static byte[] encodeUTF8(byte coder, byte[] val, boolean doReplace) { - if (coder == UTF16) + if (coder == UTF16) { return encodeUTF8_UTF16(val, doReplace); + } - if (!StringCoding.hasNegatives(val, 0, val.length)) - return Arrays.copyOf(val, val.length); + if (!StringCoding.hasNegatives(val, 0, val.length)) { + return val.clone(); + } int dp = 0; byte[] dst = new byte[val.length << 1]; @@ -1294,8 +1302,9 @@ public final class String dst[dp++] = c; } } - if (dp == dst.length) + if (dp == dst.length) { return dst; + } return Arrays.copyOf(dst, dp); }