我在一个嵌入式Linux设备上使用Java 1.5,并希望读取一个包含2MB int值的二进制文件。(目前是4字节大端,但我可以决定格式)
使用DataInputStream通过BufferedInputStream(使用dis.readInt()),这些500,000次调用需要17秒才能读取,但将文件读入一个大的字节缓冲区只需要5秒。
如何更快地将该文件读入一个巨大的int[]中?
读取过程不应使用超过另外512 kb。
以下代码使用nio方法不比java io的readInt()方法更快。
使用DataInputStream通过BufferedInputStream(使用dis.readInt()),这些500,000次调用需要17秒才能读取,但将文件读入一个大的字节缓冲区只需要5秒。
如何更快地将该文件读入一个巨大的int[]中?
读取过程不应使用超过另外512 kb。
以下代码使用nio方法不比java io的readInt()方法更快。
// asume I already know that there are now 500 000 int to read:
int numInts = 500000;
// here I want the result into
int[] result = new int[numInts];
int cnt = 0;
RandomAccessFile aFile = new RandomAccessFile("filename", "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(512 * 1024);
int bytesRead = inChannel.read(buf); //read into buffer.
while (bytesRead != -1) {
buf.flip(); //make buffer ready for get()
while(buf.hasRemaining() && cnt < numInts){
// probably slow here since called 500 000 times
result[cnt] = buf.getInt();
cnt++;
}
buf.clear(); //make buffer ready for writing
bytesRead = inChannel.read(buf);
}
aFile.close();
inChannel.close();
更新:答案的评估:
在PC上,使用Memory Map和IntBuffer的方法是我设置中最快的。
在嵌入式设备上,没有jit,java.io DataInputStream.readInt()略微更快(17秒对比Memory Map和IntBuffer的20秒)
最终结论: 通过算法变更可以更容易地实现显著的加速。(初始文件更小)