一:緩沖區是一塊特定的內存區域,其目的是通過緩解應用程序上下層之間的性能差異,減少上層對下層的等待時間,以此提高系統性能。漏斗是生活中常見的緩沖例子,下層如瓶口等工作效率低,但是上層注水口如水桶工作效率較高,他們之間使用漏斗進行緩沖,可以使上層應用抽空執行其他的任務,用以提高整體的工作效率。
二:現在我們使用java代碼執行以下程序比較有無緩沖區之間的差距:
(無緩沖區):
public class Test2 { public static void main(String[] args) { Writer writer=null; try{ writer=new FileWriter("D:\\hello.txt"); long num=10_0000; long bigTime=System.currentTimeMillis(); for(int i=0;i<num;i++){ writer.write(i); } long engTime=System.currentTimeMillis(); System.out.println("無緩沖區此時的執行時間是:"+(engTime-bigTime)+"毫秒"); }catch (Exception e){ e.printStackTrace(); }finally { try{ writer.close(); } catch (Exception e){ e.printStackTrace(); } } } }

(有緩沖區):
public class Test2 { public static void main(String[] args) { Writer writer=null; //定義緩沖流 BufferedWriter bufferedWriter=null; try{ writer=new FileWriter("D:\\hello.txt"); bufferedWriter=new BufferedWriter(writer); long num=10_0000; long bigTime=System.currentTimeMillis(); for(int i=0;i<num;i++){ bufferedWriter.write(i); } long engTime=System.currentTimeMillis(); System.out.println("有緩沖區此時的執行時間是:"+(engTime-bigTime)+"毫秒"); }catch (Exception e){ e.printStackTrace(); }finally { try{ bufferedWriter.close(); writer.close(); } catch (Exception e){ e.printStackTrace(); } } } }

我們可以明確看見加了緩沖區的代碼比不加緩沖區的代碼其性能提升了幾倍,在我們要執行數據比較龐大的任務時加緩沖區有利於提升執行性能,但是緩沖區不能太大也不能太小,根據任務適中定義。
