【问题标题】:Performance improvement of a RandomAccessBufferRandomAccessBuffer 的性能改进
【发布时间】:2014-08-14 16:29:24
【问题描述】:

我使用 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;
}

【问题讨论】:

  • 为什么不简单地将pdf文件用作RandomAccessFile?我没有看到 RandomAccessMemoryMapBuffer 引入的附加层有任何优势。
  • 没错!我也是这么想的——为什么不使用 RandomAccessFile。但是当您查看源代码时,这似乎是有症状的......

标签: java performance algorithm optimization profiling


【解决方案1】:

您在循环中一次读取一个字节(以及执行无用的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;

【讨论】:

    猜你喜欢
    • 2019-12-25
    • 2015-03-21
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多