BufferedInputStream的作用比较
參考:https://bbs.csdn.net/topics/390517474/
package com.zg.kyrie;import java.io.*;/*** @Auther: kyrie* @Date: 2018/8/23 21:50*/ public class BufferedTest{private static final String movie = "D:\\迅雷下載\\[91xinpian.com]西虹市首富HDTC1080P清晰國語中字.mp4"; // 2.54Gpublic static void main(String[] args) {long startTime1 = System.currentTimeMillis();readByBuffer(movie);long endTime1 = System.currentTimeMillis();System.out.println(endTime1 - startTime1);long startTime2 = System.currentTimeMillis();readByInput(movie);long endTime2 = System.currentTimeMillis();System.out.println(endTime2 - startTime2);}private static void readByBuffer(String movie) {BufferedInputStream bufferedInputStream = null;try{bufferedInputStream = new BufferedInputStream(new FileInputStream(movie));byte[] bytes = new byte[8192];while (bufferedInputStream.read(bytes) != -1){}} catch (IOException e){e.printStackTrace();} finally {if (bufferedInputStream != null){try{bufferedInputStream.close();} catch (IOException e){e.printStackTrace();}}}}private static void readByInput(String movie) {InputStream inputStream = null;try{inputStream = new FileInputStream(movie);byte[] bytes = new byte[8192];while (inputStream.read(bytes) != -1){}} catch (IOException e){e.printStackTrace();} finally {if (inputStream != null){try{inputStream.close();} catch (IOException e){e.printStackTrace();}}}}}第一次:bytes為8192
2000
1906
用了bufferedInputstream的比直接用inputstream耗時還要多點,可以用回帖解釋:
你這里,通過BufferedInputStream讀取用的時間比通過InputStream讀取用時時間長,是消耗在你從緩沖區(qū)里讀取數(shù)據(jù)的時間。用了BufferedInputStream后你每次讀取都是從緩沖區(qū)里拷貝數(shù)據(jù),在后你再讀,緩沖區(qū)沒東西了就調(diào)IO從數(shù)據(jù)源讀到緩沖區(qū),然后你再從緩沖區(qū)讀。為什么會這樣呢,因為你自己建立的數(shù)組大小和緩沖區(qū)大小一樣,根本就沒起到緩沖作用。
當(dāng)你程序的數(shù)組小于緩沖區(qū)的大小的時候才會起到緩沖作用。比如是byte[]?b=new?byte[2048];,你要讀的數(shù)據(jù)是1G,那么你要調(diào)512次IO,假設(shè)一次1s,就512s,但如果用BufferedInputStream,你每從緩沖區(qū)讀取4(8192/2048=4)次才調(diào)用一次IO(假設(shè)訪問內(nèi)存一次0.1s),總共要128次,就128s,加上總的從緩沖區(qū)拷貝數(shù)據(jù)的時間(512*0.1=51.2s),128+51.2=179.2。
這里用0.1s和1s來體現(xiàn)IO很耗時
?
第二次 bytes = 1024
2128
9129
明顯用了緩沖區(qū)的快樂很多。
第三次 bytes = 512
2288
17411
測試可以看出,你設(shè)定的一次讀取的字節(jié)數(shù)越少,BufferedInputStream發(fā)揮的作用越明顯。因為它都是用默認的8192大小從磁盤或者網(wǎng)絡(luò)獲取/寫入數(shù)據(jù)的,再從緩沖區(qū)讀取到bytes,直到緩沖區(qū)被讀取完畢才再通過IO讀取剩余數(shù)據(jù)。這樣就減少了很多耗時的IO讀寫操作,提高了讀寫效率。
同時可以看出,內(nèi)存間的讀取非???#xff0c;對總時長的影響很小,主要耗時在IO上,用了BufferedInputStream平均耗時都很少而且非常穩(wěn)定,所以好處很明顯啦。
?
總結(jié)
以上是生活随笔為你收集整理的BufferedInputStream的作用比较的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大数据学习——Hadoop本地模式搭建
- 下一篇: 树莓派python智能家居英文参考文献_