【发布时间】:2021-05-09 22:04:26
【问题描述】:
所以我有这个 MappedByteBuffer,其中存储了一个 int 数组(从文件中读取)。
public static void read(String loc) {
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(
Paths.get(loc), EnumSet.of(StandardOpenOption.READ))) {
MappedByteBuffer mappedByteBuffer = fileChannel
.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
if (mappedByteBuffer != null) {
IntBuffer ib = mappedByteBuffer.asIntBuffer();
mappedByteBuffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
现在,当我想从 Buffer 中读取 int 数组并在我的代码中使用它时,我必须采用以下两种方式:
方式一:(将缓冲区(ints)的内容复制到一个int数组中)
int[] ar = new int[ib.capacity];
ib.get(ar);
int int_at_index_0 = ar[0];
方式2:(直接从缓冲区读取)
ib.get(0); //reads int at index 0 directly
现在据我了解,方式 1 将存储在直接缓冲区中的数据复制到堆内存中,这是我不想要的,并且违背了使用堆外存储方式的目的。
方式 2 get(index) 方法只是耗时太长,如下数据所示:
从int[] 数组中读取:(从 ByteBuffer 复制)
ar[0] 需要 1928 纳秒。
直接从 ByteBuffer 中读取:
ib.get(0) 需要 18915 纳秒。
大不同。
有谁知道我如何从 directbuffer/mappedbytebuffer FAST 中读取而不复制到堆内存(保持在堆外)。
【问题讨论】:
-
控制台可能是限制因素。您是否尝试过不打印到控制台?
-
@codeflush.dev 我确实尝试过不打印到控制台。我通过使用 1 个索引 (0) 测量这两种方法中的每一种来测量它,因此 get(0) 和 [0] 给出了我在问题中提供的信息
标签: java arrays io heap-memory bytebuffer