简体   繁体   English

为什么GZIPInputStream需要很长时间?

[英]Why GZIPInputStream takes quite long time?

System.out.println("Input String length : " + str.length());
System.out.println("SWB==="+sw.getTime());
byte[] bytes = Base64.decodeBase64(str);
System.out.println("SWB==="+sw.getTime());
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
BufferedReader bf = new BufferedReader(new InputStreamReader(gis));
String outStr = "";
String line;
while ((line=bf.readLine())!=null) {
     outStr += line;
}
System.out.println("SWB==="+sw.getTime());
System.out.println("Output String lenght : " + outStr.length());

The above code prints 上面的代码打印

SWB===1
SWB===4
SWB===27052
Output String lenght : 1750825

But the compression of the same string takes quite short time (less than 100ms). 但是同一字符串的压缩只需要很短的时间(不到100毫秒)。 What am i doing wrong here ? 我在这里做错了什么? (other than my bad way of debug comments) (除了我不良的调试注释方式)

The problem is this: 问题是这样的:

String line;
while ((line=bf.readLine())!=null) {
     outStr += line;
}

Each String concatenation will implicitly create a StringBuilder to append the 2 strings, then call toString() method on it. 每个String串联将隐式创建一个StringBuilder来追加2个字符串,然后在其上调用toString()方法。

Use a single StringBuilder to drastically speed this up: 使用单个StringBuilder可以大大加快此速度:

StringBuilder sb = new StringBuilder(65536); // Consider a large initial size
String line
while ((line=bf.readLine())!=null) {
     sb.append(line);
}

// OutString is in the sb StringBuilder
String outStr = sb.toString();

Also consider a large initial StringBuilder size to even minimize the internal reallocations. 还应考虑使用较大的StringBuilder初始大小,以最大程度地减少内部重新分配。 In the example I used 64KB, but if you know your result String will be much bigger, you can even safely use multiple MBs. 在示例中,我使用了64KB,但是如果您知道结果String会更大,您甚至可以安全地使用多个MB。

Also consider not calling toString() on the result if you don't need it. 如果不需要,请考虑不要在结果上调用toString() StringBuilder implements CharSequence and many methods accept CharSequence as well as String s. StringBuilder实现CharSequence ,许多方法也接受CharSequence以及String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM