
bufferedinputstream转换速度优化
对于下述代码,当图片大小为5mb时,加载时间耗时8秒。如何提升其加载速度?
url url = new url(imageurl);
httpurlconnection connection = (httpurlconnection) url.openconnection();
connection.setrequestmethod("get");
connection.setconnecttimeout(5000);
bufferedinputstream bis = new bufferedinputstream(connection.getinputstream());
bytearrayoutputstream baos = new bytearrayoutputstream();
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
outputstream outputstream = response.getoutputstream();
response.setcontenttype("image/jpg");
outputstream.write(baos.tobytearray());
outputstream.flush();
outputstream.close();优化方案
该代码存在以下优化点:
优化方案一:原始流复制
优化原始流复制,通过增大缓冲区,提高效率:
httpurlconnection connection = null;
try {
url url = new url(imageurl);
connection = (httpurlconnection) url.openconnection();
connection.setrequestmethod("get");
connection.setconnecttimeout(5000);
try (inputstream bis = new bufferedinputstream(connection.getinputstream());
outputstream out = response.getoutputstream()) {
response.setcontenttype("image/jpg");
// buffer 越大,效率越快
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
out.write(buffer, 0, len);
out.flush();
}
}
} catch (exception e) {
throw new runtimeexception(e);
} finally {
if(null != connection){
connection.disconnect();
}
}优化方案二:使用复制工具
使用第三方库提供的方法复制流,减少代码复杂度:
httpurlconnection connection = null;
try {
url url = new url(imageurl);
connection = (httpurlconnection) url.openconnection();
connection.setrequestmethod("get");
connection.setconnecttimeout(5000);
try (inputstream bis = new bufferedinputstream(connection.getinputstream());
outputstream out = response.getoutputstream()) {
response.setcontenttype("image/jpg");
ioutil.copy(bis, out);
}
} catch (exception e) {
throw new runtimeexception(e);
} finally {
if(null != connection){
connection.disconnect();
}
}优化方案三:使用nio非阻塞传输
使用nio非阻塞传输,减少系统开销,提升效率:
HttpURLConnection connection = null;
try {
URL url = new URL(imageUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
try (ReadableByteChannel in = Channels.newChannel(new BufferedInputStream(connection.getInputStream()));
WritableByteChannel out = Channels.newChannel(response.getOutputStream())) {
response.setContentType("image/jpg");
ByteBuffer byteBuffer = ByteBuffer.allocate(8192);
while (in.read(byteBuffer) != -1) {
// 写转读
byteBuffer.flip();
out.write(byteBuffer);
byteBuffer.clear();
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (null != connection) {
connection.disconnect();
}
}以上就是5MB图片加载耗时8秒,如何优化BufferedInputStream的转换速度?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号