我使用 pdf 库将 PDF 转换为图像。这个过程需要很多时间,我拍了一个profiler找到问题的原因并解决所有问题(> 60% CPU 时间)的一种方法。现在我的问题是:
这个方法可以进一步改进吗?
public int read(byte[] b) throws IOException {
if (buf==null) throw new IOException("Data buffer not initialized.");
if (pointer<0 || pointer>=length)
return -1;
int length=this.length-(int)pointer;
if(length>b.length)
length=b.length;
for (int i=0; i<length; i++) {
buf.seek(pointer++);
b[i] = buf.readByte();
}
return length;
}
最佳答案
您正在循环中一次读取一个字节(以及执行无用的 seek()
)。这并不聪明,因为 RandomAccessFile
中也有一个 read(byte[] b)
方法。
改变这个
for (int i=0; i<length; i++) {
buf.seek(pointer++);
b[i] = buf.readByte();
}
到
buf.seek(pointer);
buf.read(b);
pointer += b.length;
关于java - RandomAccessBuffer 的性能改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25313085/