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();
优化方案
该代码存在以下优化点:
- 内存占用高:读取数据后全部存放在内存中,当文件较大时会造成内存溢出。
- 阻塞读取:阻塞读取数据后才执行写入,造成资源浪费。
- 连接未复用:未复用http连接,增加开销。
- 资源未释放:未释放http连接和response流,造成内存泄露。
优化方案一:原始流复制
优化原始流复制,通过增大缓冲区,提高效率:
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(); } }