Skip to content

8364320: String encodeUTF8 latin1 with negatives #26597

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/java.base/share/classes/java/lang/String.java
Original file line number Diff line number Diff line change
Expand Up @@ -1284,13 +1284,18 @@ private static byte[] encodeUTF8(byte coder, byte[] val, boolean doReplace) {
return encodeUTF8_UTF16(val, doReplace);
}

if (!StringCoding.hasNegatives(val, 0, val.length)) {
int positives = StringCoding.countPositives(val, 0, val.length);
if (positives == val.length) {
return val.clone();
}

int dp = 0;
byte[] dst = StringUTF16.newBytesFor(val.length);
for (byte c : val) {
if (positives > 0) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if for very short strings, the overhead of the setup for arraycopy is worth it.
It might be interesting to raise the test here to 4 or 8 for the array copy and otherwise start the loop at 0 and see if the performance difference is detectable.

System.arraycopy(val, 0, dst, 0, positives);
}
int dp = positives;
for (int i = dp; i < val.length; i++) {
byte c = val[i];
if (c < 0) {
dst[dp++] = (byte) (0xc0 | ((c & 0xff) >> 6));
dst[dp++] = (byte) (0x80 | (c & 0x3f));
Expand Down