Java中 BufferedInputStream/BufferedOutputStream 与 FileInputStream/FileOutputStream 性能对比测试

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时,继续扩大缓冲区会小幅增加读写时间,具体原因有待研究。

猜你喜欢

转载自www.cnblogs.com/elucidator/p/10458962.html