比较有BufferedOutputStream和无BufferedOutputStream 但使用byte[8192]的字节数组的写入速度

package xyz.jangle.io.buffered;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 比较有bufferedOutputStream和无bufferedOutputStream 但使用byte[8192]的字节数组的写入速度
 * @author jangle
 * @email 274676957@qq.com
 * 2026年1月4日 下午1:21:56
 */
public class CompareBuffered {

	/**
	 * 2026年1月4日 下午1:21:56 @author jangle
	 * @param args
	 */
	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		writeNotWithBuffer();	//370ms	63011ms
//		writeWithBuffer();		//406ms	66492ms
		long end = System.currentTimeMillis();
		System.out.println(end-start);

	}
	
	
	private static void writeWithBuffer() {
		try(InputStream fis = new FileInputStream("D:/d/test10.rar");
				OutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/d/testCompare1.rar"))){
			byte[] buf = new byte[8192];
			int len;
			while((len = fis.read(buf)) != -1) {
				bos.write(buf, 0, len);
			}
			bos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static void writeNotWithBuffer() {
		try(InputStream fis = new FileInputStream("D:/d/test10.rar");
				OutputStream fos = new FileOutputStream("D:/d/testCompare2.rar")){
			byte[] buf = new byte[8192];
			int len;
			while((len = fis.read(buf)) != -1) {
				fos.write(buf, 0, len);
			}
			fos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

单纯文件流的耗时比缓冲流的耗时少(4GB文件,单纯文件流耗时63011ms,缓冲流耗时66492ms),有两个原因:

1、缓冲区设置得和缓冲流(BufferedOutputStream)内置缓存(8192)一样大,则缓冲流没有优势,反而还多了1次内存的拷贝。

2、缓冲流的write方法有synchronized修饰,而文件流没有。多了同步的开销。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值