gpt4 book ai didi

java - 直接 java.nio.ByteBuffer 与 Java Array 性能测试

转载 作者:行者123 更新时间:2023-11-30 06:40:02 25 4
gpt4 key购买 nike

我想比较直接字节缓冲区(java.nio.ByteBuffer,堆外)和堆缓冲区(通过数组实现)的读取和写入性能。我的理解是,堆外的 ByteBuffer 比堆缓冲区至少有两个好处。首先,它不会被考虑用于 GC,其次(我希望我做对了)JVM 在读取和写入时不会使用中间/临时缓冲区。这些优点可能使堆外缓冲区比堆缓冲区更快。如果那是正确的,我不应该期望我的基准测试显示相同吗?它总是比非堆缓冲区更快地显示堆缓冲区。

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Fork(value = 2, jvmArgs = {"-Xms2G", "-Xmx4G"})
@Warmup(iterations = 3)
@Measurement(iterations = 10)
public class BasicTest {

@Param({"100000"})
private int N;

final int bufferSize = 10000;

ByteBuffer byteBuffer = ByteBuffer.allocateDirect(8 * bufferSize);
long buffer[] = new long[bufferSize];


public static void main(String arep[]) throws Exception {

Options opt = new OptionsBuilder()
.include(BasicTest.class.getSimpleName())
.forks(1)
.build();

new Runner(opt).run();

}


@Benchmark
public void offHeapBuffer(Blackhole blackhole) {

IntStream.range(0, bufferSize).forEach(index -> {
byteBuffer.putLong(index, 500 * index);
blackhole.consume(byteBuffer.get(index));
});

}

@Benchmark
public void heapBuffer(Blackhole blackhole) {

IntStream.range(0, bufferSize).forEach(index -> {
buffer[index] = 500 * index;
blackhole.consume(buffer[index]);
});

}
}

Run complete. Total time: 00:00:37

Benchmark (N) Mode Cnt Score Error Units

BasicTest.heapBuffer 100000 avgt 10 0.039 ± 0.003 ms/op

BasicTest.offHeapBuffer 100000 avgt 10 0.050 ± 0.007 ms/op

最佳答案

It won't be considered for GC

当然会考虑GC。

垃圾收集器确定缓冲区不再使用,然后释放内存。

Should I not expect my benchmark to show [that] off-heap buffer [is] faster than heap buffer?

堆外并不能使缓冲区更快地进行内存访问。

当 Java 与操作系统交换缓冲区中的字节时,直接 缓冲区会更快。由于您的代码不执行 I/O,因此使用直接缓冲区没有性能优势。

作为javadoc说:

Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer's content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system's native I/O operations.

关于java - 直接 java.nio.ByteBuffer 与 Java Array 性能测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59008751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com