为什么缓冲流更快的验证
来源:3-14 缓冲流案例
WittChen
2021-01-24 15:10:41
自己提的问题以及观点,自己给自己验证,望老师耐心查看
https://class.imooc.com/course/qadetail/274963
1、上个问题中我提出了是,之所以缓冲流更开是优化了直接读写硬盘的操作次数,
以下代码给予验证
验证只缓冲流快与普通流
普通读写流
public class CopytImage {
public static void main(String[] args) {
File file1 = new File("sads.jpg");
try {
file1.createNewFile();
Date date1 = new Date();
FileInputStream fis = new FileInputStream("sda.jpg");
FileOutputStream fos = new FileOutputStream(file1);
byte[] by = new byte[1024];
int n = 0;
while((n = fis.read(by)) != -1) {
fos.write(by, 0, n);
}
fis.close();
fos.close();
Date date2 = new Date();
System.out.println("普通流读写4m大小图片速度" + (date2.getTime() - date1.getTime()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果:普通流读写4m大小图片速度68
缓冲流
public class BufferCopyImage {
public static void main(String[] args) {
File file1 = new File("sda.jpg");
File file2 = new File("sads.jpg");
try {
file2.createNewFile();
Date date1 = new Date();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file1));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file2));
int n = 0;
byte[] by = new byte[1024];
while((n = bis.read(by)) != -1) {
bos.write(by, 0, n);
}
bis.close();
bos.flush();
bos.close();
Date date2 = new Date();
System.out.println("缓冲流读写4m大小图片速度" + (date2.getTime() - date1.getTime()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}
结果:缓冲流读写4m大小图片速度21
从上面结果可以看出,确实缓冲流快,那么真的缓冲流不管什么时候都快吗
缓冲流2
public class BufferCopyImage {
public static void main(String[] args) {
File file1 = new File("sda.jpg");
File file2 = new File("sads.jpg");
try {
file2.createNewFile();
Date date1 = new Date();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file1), 1);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file2), 1);
int n = 0;
byte[] by = new byte[1024];
while((n = bis.read(by)) != -1) {
bos.write(by, 0, n);
}
bis.close();
bos.flush();
bos.close();
Date date2 = new Date();
System.out.println("缓冲流读写4m大小图片速度" + (date2.getTime() - date1.getTime()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}
结果:缓冲流读写4m大小图片速度80
这里可以看出缓冲流竟然慢与普通六=流,以上代码,我把缓冲区的大小改为了极限的1值,也就是说只要有一个字符我就开始读写,这样极大的增加了,直接读写硬盘的次数,那么自然也就慢了,当我改成40000它的速度比默认不设置值更快,默认应该是8000吧,这是我的验证
1回答
同学你好,同学的验证是合理的
如果没有缓冲区,应用程序每次读写都要和设备进行通信,效率很低;如果有缓冲区,为了提高效率,当写入设备时,先写入缓冲区,等到缓冲区有足够多的数据时,就整体写入设备,从而避免了每一个数据都和IO进行一次交互
如果把缓冲区的大小设置为1时,读取一个字节存入了缓存区,缓存区满了,将数据写入设备,这样也是每一个数据都和IO进行一次交互,并且又增加了存入缓冲区的时间,所以当缓冲区的大小为1时,读写速度会比普通流还慢
缓冲区大小默认是8192字节,但是并不是缓冲区的值越大越好,所以一般我们都使用默认大小,如下,这里同学了解就可以,如果同学感兴趣可以查询下相关资料


祝学习愉快~
相似问题