我有一个 http 客户端,它获取包含 png 图像字符串的 json 响应,然后我将其旋转。
一切都按预期工作,但我很好奇为什么(方法1)在旋转之前将http响应图像作为BufferedImage保存在内存中所说的BufferdImage比(方法2)将http响应图像保存到文件然后读取要慢在旋转同一个 BufferedImage 之前将该文件转换为 BufferedImage?
这与我们都知道的相反,即在内存中进行类似的读/写操作比文件 i/o 更快。我运行java的笔记本电脑有充足的内存和磁盘空间。
////////////METHOD 1 - WRITE/READ IMAGE FROM MEMORY
log.info("START TEST1 " + new Timestamp(System.currentTimeMillis()));
OutputStream outputStream = null;
byte[] imageByteArray =
Base64.decodeBase64(jsonObj.getString("LabelImages"));
//Convert byte array back to BufferedImage
InputStream in = new ByteArrayInputStream(imageByteArray);
BufferedImage img = ImageIO.read(in);
BufferedImage rotatedImg = rotate(img, 90);
File outputfile = new File("/var/opt/DI/tmp/rotatedlabel" + orderId + ".png");
ImageIO.write(rotatedImg, "png", outputfile);
log.info("END TEST1 " + new Timestamp(System.currentTimeMillis()));
////////////METHOD 2 - WRITE/READ IMAGE FROM FILE
log.info("START TEST2 " + new Timestamp(System.currentTimeMillis()));
writeImageStringToFile(jsonObj.getString("LabelImages"), orderId);
BufferedImage rotatedImg2 = rotate(ImageIO.read(new
File("/var/opt/DI/tmp/label" + orderId + ".png")), 90);
File outputfile2 = new
File("/var/opt/openbravo/bluecrest/DI/tmp/rotatedlabel" + orderId + ".png");
ImageIO.write(rotatedImg2, "png", outputfile2);
log.info("END TEST2 " + new Timestamp(System.currentTimeMillis()));
METHOD 2 is about 10% faster than METHOD 1.
最佳答案
您需要告诉我们您是如何进行性能测试的。如果你按照这里写的那样做(在同一个程序中调用方法1,然后调用方法2),我的猜测是,这是由于JIT在方法1期间优化了旋转方法,并在方法2期间享受了这种优化,以至于它克服了磁盘问题操作。
就我个人而言,当我进行性能比较测试时,我会在程序中运行 method1 大约 10 次,消除两到三个最差的结果,然后在单独的程序中对 method2 执行相同的操作。这通常会给 JIT 足够的时间来启动并提供更有意义的数字。
关于Java 从文件读取/写入 BufferedImage 性能与内存的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56299857/