我尝试过gzip一个大型(100 do到500 do) xml文件,我创建了方法Zip。问题是,它对zip.for 200 xml的时间太长,需要1.2秒。我需要减少100毫秒的时间来处理100 xml的xml文件。如何优化以减少拉链的时间?
我减少了时间,减少了对压缩比的小妥协。尝试了另一种算法,如Snappy、Lz4,但改进不多,而且它们的compression.as也很差,据我所知,gzipOutputStream.write()占用了85%的time.so,如何优化这个步骤以获得更好的性能,而不影响很大程度的压缩比。
public static String zip(final String str) {
if ((str == null) || (str.length() == 0)) {
throw new IllegalArgumentException("Cannot zip null or empty string");
}
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(str.length())) {
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream){{def.setLevel(Deflater.BEST_SPEED );}};) {
gzipOutputStream.write(str.getBytes(StandardCharsets.UTF_8));
}
T5 = System.currentTimeMillis();
byte[] bytes=byteArrayOutputStream.toByteArray();
T3 = System.currentTimeMillis();
String zipped_text=DatatypeConverter.printBase64Binary(bytes);
T4 = System.currentTimeMillis();
return zipped_text;
} catch(IOException e) {
throw new RuntimeException("Failed to zip content", e);
}
}发布于 2019-05-06 12:10:56
以下是我的建议:
(出于各种原因,我不会简单地依赖于对System.currentTimeMillis()的调用。)
一种可能的解释是,在以下步骤中,很大一部分时间用于数据复制。
ByteArrayOutputStream中的压缩字节因此,如果您正在寻找改善这种情况的方法,请尝试安排一些事情,以便XML序列化程序写入通过gzip和base64转换流数据的管道,然后直接写入文件或套接字流。
此外,如果可能的话,我将避免使用base64。如果压缩的XML位于HTTP响应中,则应该能够以二进制方式发送它。它将更快,并产生明显较少的网络流量。
最后,选择一种压缩算法,在压缩比和压缩时间之间做出很好的折中。
如何优化这一步骤,以获得更好的性能,而不影响压缩比。
如果你想这么做,你的目标可能是错的。(那么为什么Base64会对压缩文件进行编码呢?这违背了你的目标!)
更新以回应您的评论:
getBytes()。首先,getBytes()调用正在对字符串内容进行不必要的复制。- you can dispense with the base64, saving ~25% storage space
- you can dispense with the base64 encoding step, saving a few percent of CPU
- you can then pick a faster (but less compact) algorithm, saving more time at the cost of some of the space that you saved by going to a BLOB.
https://stackoverflow.com/questions/56004422
复制相似问题