Java有缓冲与无缓冲读写效率对比

将1~100000整数写入(读取)out.txt文件中,记录不同写入方式的运行时间

一、无缓冲写
public class Main {
    public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("D:\\out.txt");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1e6; ++i) {
            fos.write(i);
        }
        fos.close();
        long end = System.currentTimeMillis();
        System.out.println("time = " + (end - start) + "ms");
    }
}

用时:2053ms

二、有缓冲写

BufferedOutputStream提供了一个byte数组作为缓冲区,默认大小为8KB。缓冲区写满后才会真正地写入磁盘。

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("D:\\out.txt"));
        long start = System.currentTimeMillis();
        for (int i = 1; i <= 1e6; ++i) {
            fos.write(i);
        }
        fos.flush();
        fos.close();
        long end = System.currentTimeMillis();
        System.out.println("time = " + (end - start) + "ms");
    }
}

用时:53ms

在创建BufferedOutputStream对象时也可以指定缓冲区大小,当指定为1时,又变为了无缓冲写。

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("D:\\out.txt"), 1);
        long start = System.currentTimeMillis();
        for (int i = 1; i <= 1e6; ++i) {
            fos.write(i);
        }
        fos.flush();
        fos.close();
        long end = System.currentTimeMillis();
        System.out.println("time = " + (end - start) + "ms");
    }
}

用时:2117ms

三、无缓冲读
public class Main {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:\\out.txt");
        int b = 0;
        long start = System.currentTimeMillis();
        while ((b = fis.read()) != -1);
        fis.close();
        long end = System.currentTimeMillis();
        System.out.println("time = " + (end - start) + "ms");
    }
}

用时:1757ms

四、有缓冲读
public class Main {
    public static void main(String[] args) throws Exception {
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream("D:\\out.txt"));
        int b = 0;
        long start = System.currentTimeMillis();
        while ((b = fis.read()) != -1);
        fis.close();
        long end = System.currentTimeMillis();
        System.out.println("time = " + (end - start) + "ms");
    }
}

用时:19ms

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值