Skip to content

性能微优化-base64

About 345 wordsAbout 1 min

性能新书

2026-08-20

6.10 Base64

Base64是一种能将任意二进制用64种字符组合成字串的方法,而这个二进制和字符串彼此之间是可以互相转换的。在实际应用上,可以将二进制通过文本方式表达。使用HTTP协议发送图片等二进制内容,可以转成Base64字符串发送,服务器端然后解码获取图片内容。 通常有三种方法能实现Base64转化

  • 较早使用sun.misc下的BASE64Encoder和BASE64Decoder
  • Apache Commons Codec有提供rg.apache.commons.codec.binary.Base64的编码与解码功能
  • Java8提供了java.util.Base64
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Threads(1)
@Fork(1)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
public class Base64Test {
    /*sun*/
    BASE64Encoder sunBase64Encoder = new BASE64Encoder();
    BASE64Decoder sunBase64Decoder = new BASE64Decoder();
    /*apache*/
    Base64 apacheBase64 = new Base64();
    /*jdk8*/
    java.util.Base64.Decoder jdk8Base64Decoder =  java.util.Base64.getDecoder();
    java.util.Base64.Encoder jdk8Base64Encoder =  java.util.Base64.getEncoder();


    byte[] content = "<xml><element>hello,world</element></xml>".getBytes(StandardCharsets.UTF_8);

    @Benchmark
    public byte[] sun() throws IOException {
            String str = sunBase64Encoder.encode(content);
            byte[] bs = sunBase64Decoder.decodeBuffer(str);
            return bs;
    }

    @Benchmark
    public byte[] apache() throws IOException {
            String str = apacheBase64.encodeToString(content);
            byte[] bs = apacheBase64.decode(str);
            return bs;
    }

    @Benchmark
    public byte[] jdk8() throws IOException {
            String str = jdk8Base64Encoder.encodeToString(content);
            byte[] bs = jdk8Base64Decoder.decode(str);
            return bs;
    }


    public static void main(String[] args) throws RunnerException {
            Options opt = new OptionsBuilder().include(Base64Test.class.getSimpleName()).forks(1).build();
            new Runner(opt).run();
    }
}

测试结果表明jdk8的性能远远高于另外两种方式,

Benchmark                     Mode  Samples     Score  Score error   Units
c.i.c.c.Base64Test.apache    thrpt        5   454.697      650.348  ops/ms
c.i.c.c.Base64Test.jdk8      thrpt        5  3509.271      617.351  ops/ms
c.i.c.c.Base64Test.sun       thrpt        5   213.630       12.606  ops/ms

知行合一