BufferedInputStream/BufferedOutputStream在文件I/O過程中使用了緩沖區,從而提高了I/O性能。具體提升多少?下面進行測試
測試環境:
CPU:i3-4160 @3.6GHz
內存:4G DDR3 @1333MHz
硬盤:WDC_WD5000AAKX-08U6AA0 ATA
系統:Windows 7 旗艦版
采用文件加密與解密的方法對BufferedInputStream/BufferedOutputStream進行測試,對象文件為exe應用程序,大小4.3MB。
加密與解密的方法見我之前寫的博客:Java文件加密與解密
測試方法如下
public static void main(String[] args) { String path = "osu!install.exe"; File file = new File(path); long start = System.currentTimeMillis(); EncryptionAndDeciphering.encryptFile(file); EncryptionAndDeciphering.decipherFile(new File("Encrypted_osu!install.exe")); long end = System.currentTimeMillis(); int time = (int) ((end - start)); System.out.println("Time:" + time); }
先加密osu!install.exe,產生Encrypted_osu!install.exe,再解密Encrypted_osu!install.exe。
測試結果如下,單位毫秒。
其中緩沖區大小為0代表直接使用FileInputStream/FileOutputStream。
可以看到,使用BufferedInputStream/BufferedOutputStream的平均時間為199ms,而使用FileInputStream/FileOutputStream的平均時間為39535ms,是前者的198.7倍,可見緩沖區的使用極大的提高了I/O性能。
那么具體緩沖區設置多大合適?
從上表可以看出,緩沖區特別小的時候,讀寫時間還是比較長。但當緩沖區超過1024Bytes是,測試結果已經相差不大,都在300ms以內了。但當緩沖區超過默認值8192Bytes時,繼續擴大緩沖區會小幅增加讀寫時間,具體原因有待研究。