我正在从文件中加载一个2D数组,它是15,000,000*3整数(最终将是40,000,000*3).现在,我dataInputStream.readInt()用来顺序读取整数.大约需要15秒.我可以使它显着(至少3倍)更快或者这个速度和我一样快吗?
将文件映射到内存中!
Java 7代码:
FileChannel channel = FileChannel.open(Paths.get("/path/to/file"),
StandardOpenOption.READ);
ByteBuffer buf = channel.map(0, channel.size(),
FileChannel.MapMode.READ_ONLY);
// use buf
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参见此处
如果您使用Java 6,则必须:
RandomAccessFile file = new RandomAccessFile("/path/to/file", "r");
FileChannel channel = file.getChannel();
// same thing to obtain buf
Run Code Online (Sandbox Code Playgroud)
.asIntBuffer()如果需要,您甚至可以在缓冲区上使用.当您需要阅读时,您只能阅读实际需要阅读的内容.而且它不会影响您的堆.
Yes, you can. From benchmark of 13 different ways of reading files:
If you have to pick the fastest approach, it would be one of these:
FileChannel with a MappedByteBuffer and array reads.FileChannel with a direct ByteBuffer and array reads.FileChannel with a wrapped array ByteBuffer and direct array access.For the best Java read performance, there are 4 things to remember:
BufferedInputStream).FileChannel和的非线程安全类MappedByteBuffer.FileChannel内存映射,或直接或包装数组ByteBuffer.