patternjavaMinor
Decrease Image downloading time with HttpURLConnection
Viewed 0 times
imagewithdownloadingtimehttpurlconnectiondecrease
Problem
This is piece of code is using to download images. Can somebody tell me how to optimize this code to decrease download time for each image?
URL url;
HttpURLConnection connection = null;
InputStream input = null;
System.setProperty("http.keepAlive", "true");
try {
url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(HTTP_CONNECTION_TIMEOUT);
connection.setRequestProperty("Connection", "Keep-Alive");
input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
currentRequestInProgress.remove(urlString);
if (connection != null)
connection.disconnect();
if(input != null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}Solution
Buffered streams usually result in greatly improved performance:
The buffer size is 8kb per default, tuning it may be an option (but not without measuring).
And, if you download multiple images: parallelize it with multiple threads (most of the time is consumed by I/O waits anyway), this usually improves performance by factors.
input = new BufferedInputStream(connection.getInputStream());The buffer size is 8kb per default, tuning it may be an option (but not without measuring).
And, if you download multiple images: parallelize it with multiple threads (most of the time is consumed by I/O waits anyway), this usually improves performance by factors.
Code Snippets
input = new BufferedInputStream(connection.getInputStream());Context
StackExchange Code Review Q#46711, answer score: 6
Revisions (0)
No revisions yet.