简体   繁体   English

在 Java 中将字符串转换为 ByteBuffer

[英]Converting a String to ByteBuffer in Java

I want to convert an ASCII string to a ByteBuffer and I came across these two approaches:我想将 ASCII 字符串转换为 ByteBuffer,我遇到了这两种方法:

ByteBuffer.wrap(str.getBytes(StandardCharsets.US_ASCII));

and

StandardCharsets.US_ASCII.encode(str);

What is their difference (maybe in terms of performance too)?它们有什么区别(也许在性能方面也是如此)? Would these produce the same result?这些会产生相同的结果吗?

getBytes uses the platforms default charset, not necessarily ASCII. getBytes使用平台默认字符集,不一定是 ASCII。

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.使用平台的默认字符集将此字符串编码为字节序列,并将结果存储到新的字节数组中。

StandardCharsets.US_ASCII.encode actually uses ASCII. StandardCharsets.US_ASCII.encode实际上使用 ASCII。

If you use str.getBytes(StandardCharsets.US_ASCII) , however, then they will be do the same thing on a high level.但是,如果您使用str.getBytes(StandardCharsets.US_ASCII) ,那么它们将在较高级别上执行相同的操作。

After a quick look into their implementations, getBytes seems to do a very different thing from encode , so to find out which one is quicker in terms of performance, you'd have to do a benchmark.在快速查看他们的实现之后, getBytes似乎做了一件与encode非常不同的事情,所以要找出哪个在性能方面更快,你必须做一个基准测试。

EDIT:编辑:

I wrote a JMH benchmark:我写了一个 JMH 基准测试:

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 10)
@Fork(value = 1)
public class Main {

    static final String s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

    public static void main (String args[]) throws IOException, RunnerException {
        org.openjdk.jmh.Main.main(args);
    }

    @Benchmark
    public void wrap(Blackhole bh) {

        bh.consume(ByteBuffer.wrap(s.getBytes(StandardCharsets.US_ASCII)));
    }

    @Benchmark
    public void encode(Blackhole bh) {
        bh.consume(StandardCharsets.US_ASCII.encode(s));
    }
}

This is the result:这是结果:

Benchmark    Mode  Cnt     Score    Error  Units
Main.encode  avgt   20  2407.242 ± 28.147  ns/op
Main.wrap    avgt   20   199.227 ±  4.093  ns/op

So wrap is a lot faster.所以wrap要快得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM