简体   繁体   中英

BufferedReader running extremely slow

I'm downloading an image from my web server like this:

conn = url.openConnection();
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((resp = rd.readLine()) != null) {
    downloadedImage += resp;
}

However it's extremely slow. Downloading a single 500kb file takes about 15 seconds. Is there a better way to download the image?

Incase it matters: The file formatted as x lines, 80 UTF-8 chars each. Keeping the line breaks isn't important.

Thanks

I guess the weakest link here is the network / server, but anyway, you could improve performance of the while loop a little bit.

Using += basically creates a new StringBuilder each time you invoke it. So string1 += string2 is the same thing as invoking string1 = new StringBuilder(string1).append(string2).toString(); Obviously, you would never do this in a loop that runns x times. So instead create one StringBuilder before you start the loop, and call toString() after finishing.

StringBuilder stringBuilder = new StringBuilder(downloadedImage);
while ((resp = rd.readLine()) != null) {
    stringBuilder.append(resp);
}
downloadedImage = stringBuilder.toString();

If the loop doesn't run often, the performance improvement might not be as big, but since you're downloading an Image I suppose it runs quite a few times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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