8378698: Optimize Base64.Encoder#encodeToString

Reviewed-by: liach, rriggs
This commit is contained in:
Patrick Strawderman 2026-03-04 20:04:30 +00:00 committed by Chen Liang
parent 9d1d0c6f05
commit 08c8520b39
2 changed files with 59 additions and 2 deletions

View File

@ -32,6 +32,8 @@ import java.io.OutputStream;
import java.nio.ByteBuffer;
import sun.nio.cs.ISO_8859_1;
import jdk.internal.access.JavaLangAccess;
import jdk.internal.access.SharedSecrets;
import jdk.internal.util.Preconditions;
import jdk.internal.vm.annotation.IntrinsicCandidate;
@ -201,6 +203,7 @@ public final class Base64 {
* @since 1.8
*/
public static class Encoder {
private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
private final byte[] newline;
private final int linemax;
@ -344,10 +347,9 @@ public final class Base64 {
* the byte array to encode
* @return A String containing the resulting Base64 encoded characters
*/
@SuppressWarnings("deprecation")
public String encodeToString(byte[] src) {
byte[] encoded = encode(src);
return new String(encoded, 0, 0, encoded.length);
return JLA.uncheckedNewStringWithLatin1Bytes(encoded);
}
/**

View File

@ -0,0 +1,55 @@
/*
* Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.micro.bench.java.util;
import org.openjdk.jmh.annotations.*;
import java.util.Base64;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@State(Scope.Benchmark)
@Warmup(iterations = 5, time = 2)
@Measurement(iterations = 5, time = 2)
@Fork(value = 2)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class Base64EncodeToString {
private byte[] input;
@Param({"10", "100", "1000", "10000"})
private int inputSize;
@Setup
public void setup() {
Random r = new Random(1123);
input = new byte[inputSize];
r.nextBytes(input);
}
@Benchmark
public String testEncodeToString() {
return Base64.getEncoder().encodeToString(input);
}
}