JAVA FileInputStream 与 BufferedInputStream读取效率的比较

来源:互联网 发布:软件开发毕业设计题目 编辑:程序博客网 时间:2024/06/05 23:45
有人在网上做过这样一个实验:
代码如下
importjava.io.BufferedInputStream;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
publicclassInputStreamTest {
   privatestaticfinalStringFILENAME="C:\\Users\\lchen4\\Downloads\\Evernote_6.2.4.3244.exe";
   publicstaticvoidmain(String[] args)throwsIOException {
       longl1 =readByBufferedInputStream();
       longl2 =readByInputStream();
        System.out.println("通过BufferedInputStream读取用时:"+l1+";通过InputStream读取用时:"+l2);
    }
   publicstaticlongreadByInputStream()throwsIOException {
        InputStreamin=newFileInputStream(FILENAME);
       byte[] b=newbyte[8000];
       intl=0;
       longstart=System.currentTimeMillis();
       while(in.read(b,0,8000)!=-1){
        }
       longend=System.currentTimeMillis();
       returnend-start;
    }
   publicstaticlongreadByBufferedInputStream()throwsIOException {
        BufferedInputStreamin=newBufferedInputStream(newFileInputStream(FILENAME));
       byte[] b=newbyte[8000];
       intl=0;
       longstart=System.currentTimeMillis();
       while(in.read(b,0,8000)!=-1){
        }
       longend=System.currentTimeMillis();
       returnend-start;
    }
}


读取大小为8000时候的测试结果:
通过BufferedInputStream读取用时:113;通过InputStream读取用时:74

读取大小为128时候的测试结果:
通过BufferedInputStream读取用时:114;通过InputStream读取用时:1283

网友的疑问是,为什么我们用了buffer(BufferedInputStream )花的时间还比没用的时候长?
首先我们关注他们的读取:
in.read(b,0,8000)
in read(byte b[], int off, int len)
b[]-目标byte数组
off 表示读取的起始位置
len 表示要读取的长度

BufferedInputStream中:
byte[] buf,在读取的时候,我们会优先检查buf中的数据。这个buf的默认大小是8M
pos 表示上一次读取的最后的位置
count表示buf中index的最后一位。buf的范围在buf[0]-buf[count-1]之间
那么:pos>=count,表示已经读到buf的末尾,我们自动填充buf
否者:pos<count,我们从buf中读取。

当我们一次读取的数据len为8000的时候,他一次读取的大小接近buf的总长度了(8192),几乎此读取BufferedInputStream都要重新填充一次buf,那还不如直接从文件读取效率高,因为还有填充一次buf再从buf读取。
然后我们把len的大小都修改为128的时候,BufferedInputStream要读取65次这样的循环in.read(b,0,128)才会触发一次fill()方法去填充buf.这样才能提高效率。
这就是我理解的原因。
所以请不要把你要读取的byte[]长度设置的和buf的缓存区差不多大。任何东西都不是一定快和一定慢的。都是因情况而定的。





1 0
原创粉丝点击