黑马程序员技术交流社区
标题:
字节流缓冲区的效率真的那么高么。
[打印本页]
作者:
1017161726
时间:
2015-6-7 23:03
标题:
字节流缓冲区的效率真的那么高么。
首先,我没用缓冲区,也不用临时数组,来复制一个6M的图片。
耗时大概45000毫秒,代码如下:
import java.io.*;
class Demo {
public static void main(String [] args) {
FileInputStream fin=null;
FileOutputStream fout=null;
try {
fin=new FileInputStream("1.jpg");
fout=new FileOutputStream("copy.jpg");
long L1=System.currentTimeMillis();
int n=0;
while ((n=fin.read())!=-1) {
fout.write(arr,0,n);
}
long L2=System.currentTimeMillis();
System.out.println(L2-L1);
}
catch (IOException e) { throw new RuntimeException("读写失败"); }
finally {
if (fin!=null)
try { fin.close(); } catch (IOException e) { throw new RuntimeException("读取关闭失败"); }
if (fout!=null)
try { fout.close(); } catch (IOException e) { throw new RuntimeException("写入关闭失败"); }
}
}
}
复制代码
然后,我不缓冲区,用8192容量的临时数组,复制这个图片。
耗时大概15毫秒,部分代码如下:
fin=new FileInputStream("1.jpg");
fout=new FileOutputStream("copy.jpg");
long L1=System.currentTimeMillis();
byte [] arr=new byte[1024*8];
int n=0;
while ((n=fin.read(arr))!=-1) {
fout.write(arr,0,n);
}
long L2=System.currentTimeMillis();
System.out.println(L2-L1);
复制代码
是不是差距特别大。。。你们也可以试试结果.
然后,看看用字节流缓冲区的效率。
缓冲区内部封装默认大小8192的字节数组,这里直接读取,代码如下:
import java.io.*;
class Demo {
public static void main(String [] args) {
BufferedInputStream bin=null;
BufferedOutputStream bout=null;
try {
bin=new BufferedInputStream(new FileInputStream("1.jpg"));
bout=new BufferedOutputStream(new FileOutputStream("copy.jpg"));
long L1=System.currentTimeMillis();
int n=0;
while ((n=bin.read())!=-1) {
bout.write(n);
}
long L2=System.currentTimeMillis();
System.out.println(L2-L1);
}
catch (IOException e) { throw new RuntimeException("读写失败"); }
finally {
if (bin!=null)
try { bin.close(); } catch (IOException e) { throw new RuntimeException("读取关闭失败"); }
if (bout!=null)
try { bout.close(); } catch (IOException e) { throw new RuntimeException("写入关闭失败"); }
}
}
}
复制代码
耗时大概333毫秒,不见得多高效。
然后用字节流缓冲区加上临时字节数组,来看看效率,代码如下:
bin=new BufferedInputStream(new FileInputStream("1.jpg"));
bout=new BufferedOutputStream(new FileOutputStream("copy.jpg"));
long L1=System.currentTimeMillis();
byte [] arr=new byte[1024*8];
int n=0;
while ((n=bin.read(arr))!=-1) {
bout.write(arr,0,n);
}
long L2=System.currentTimeMillis();
System.out.println(L2-L1);
复制代码
耗时大概15毫秒,也是最高效方法之一了。
然后我又把字节数组的大小改成100k,
耗时大概7毫秒,代码不另附。
字节流的缓冲区效率也就那回事。
怎么解释。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2