缓存与缓存的区别
1.1、缓冲 Buffer
很多时候上层应用的数据传输效率远远大于下次应用,所以要传输数据就要需要上层应用等待下层应用接收数据,会浪费很多时间
缓冲的作用就是协调上下层应用之间的性能差异,可以有效减少上层组件对下层组件的等待时间,可提升整个系统的性能
当需要把一盆水倒入一个细口瓶时,缓冲区就像中间的一个漏斗,可以将水(数据)完完整整且以较高效率的倒入瓶中
1.2、测试
//使用缓冲区BufferedWriter 将0-1000000的数字输出到指定文件private static void testBuffer() {try {BufferedWriter bw=new BufferedWriter(new FileWriter("textBuffer.txt"));int num = 1000000;long beginTime=System.currentTimeMillis();for(int i=0;i<num;i++){bw.write(i);}long endTime=System.currentTimeMillis();System.out.println(endTime-beginTime);} catch (IOException e) {e.printStackTrace();}}
平均用时60ms
//不用缓冲区 使用普通Writerpublic static void test() {Writer writer = null;try {writer = new FileWriter("textBuffer.txt");int num = 10000;long beginTime=System.currentTimeMillis();for(int i=0;i<num;i++){writer.write(i);}long endTime=System.currentTimeMillis();System.out.println(endTime-beginTime);} catch (IOException e) {e.printStackTrace();}finally {try {writer.close();} catch (IOException e) {e.printStackTrace();}}}
用时138ms左右
1.3、BufferWriter 的两个构造函数
BufferedWriter(Writer writer);BufferedWriter(Writer writer,int size);
- BufferedWriter 默认创建8KB的缓冲区
- BufferedWriter 中的size参数即可以自己指定缓冲大小
2.1、缓存 Cache
缓存是为了提升系统性能而开辟的一块空间,与缓冲不同的是,缓存是将被反复使用的数据存储起来,供程序直接调用,避免程序反复的从数据库中读取相同的数据。
