不加缓存
// @Test
public void Demo1() throws IOException{
long t1 = System.currentTimeMillis();
DataInputStream din = new DataInputStream(
new FileInputStream(FILE_NAME)
);
String str = null;
while( (str=din.readLine())!=null){
System.out.println(str);
}
long t2 = System.currentTimeMillis();
System.out.println("不加缓存运行时间"+(t2-t1));
// test1=16080,15975,15777,15403,15421,16018
}
缓存加载内部
@Test
public void Demo2() throws IOException{
long t1 = System.currentTimeMillis();
DataInputStream din = new DataInputStream(
new BufferedInputStream(
new FileInputStream(FILE_NAME))
);
String str = null;
while((str=din.readLine())!=null){
System.out.println(str);
}
long t2 = System.currentTimeMillis();
System.out.println("缓存加在内部时间:"+(t2-t1));
// test2 = 7057,6873,6843,6711,7292,7264
缓存加在外部
@Test
public void Demo3() throws IOException{
long t1 = System.currentTimeMillis();
BufferedInputStream din = new BufferedInputStream(
new DataInputStream(
new FileInputStream(FILE_NAME))
);
String str = null;
byte buf[] = new byte[1000];
int len=0;
while((len=din.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
long t2 = System.currentTimeMillis();
System.out.println("缓存加在内部时间:"+(t2-t1));
//test 3=7305,7145,7291 (30)
//test 3=6924, 6691, 6354,7063,6664(160)
//test 3=6829,6910,6709,6591,6758(500)
//test 3=6742,6678,6830,7134(1000)
}
最后呢,我发现加缓存比不加缓存明显快的多,两种加缓存方式感觉差不多。可能是测试数据只有5M 的原因吧
1)有buffer比没有更快
2)buffer放在中间层包装比放在外层更快;
3)按行或按块操作 比 按字节或字符操作更快(用Object流操作的速度 比 字节字符方式 更快)
4)缓冲区要结合流才可以使用,在流的基础上对流的功能进行了增强