缓冲流效率测试

查询 API,缓冲流读写方法与基本的流是一致的,我们通过复制大文件(375 MB),测试它的效率;

1. 基本流

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

public class Test {

public static void main(String[] args) throws FileNotFoundException {

// 记录开始时间

long start = System.currentTimeMillis();

// 创建流对象,外汇出入金流程http://www.fx61.com/support

try (

FileInputStream fis = new FileInputStream("jdk8.exe");

FileOutputStream fos = new FileOutputStream("copy.exe")

) {

// 读写数据

int b;

while ((b = fis.read()) != -1) {

fos.write(b);

}

} catch (IOException e) {

e.printStackTrace();

}

// 记录结束时间

long end = System.currentTimeMillis();

System.out.println("普通流复制时间:" + (end - start) + " 毫秒");

}

}

十几分钟过去了…

2. 缓冲流

import java.io.*;

public class Test {

public static void main(String[] args) throws FileNotFoundException {

// 记录开始时间

long start = System.currentTimeMillis();

// 创建流对象

try (

BufferedInputStream bis = new BufferedInputStream(new

FileInputStream("jdk8.exe"));

BufferedOutputStream bos = new BufferedOutputStream(new

FileOutputStream("copy.exe"));

) {

// 读写数据

int b;

while ((b = bis.read()) != -1) {

bos.write(b);

}

} catch (IOException e) {

e.printStackTrace();

}

// 记录结束时间

long end = System.currentTimeMillis();

System.out.println("缓冲流复制时间:" + (end - start) + " 毫秒");

}

}

缓冲流复制时间:8016 毫秒;

如何更快呢?我们可以使用数组的方式:

import java.io.*;

public class Test {

public static void main(String[] args) throws FileNotFoundException {

// 记录开始时间

long start = System.currentTimeMillis();

// 创建流对象

try (

BufferedInputStream bis = new BufferedInputStream(new

FileInputStream("jdk8.exe"));

BufferedOutputStream bos = new BufferedOutputStream(new

FileOutputStream("copy.exe"));

) {

// 读写数据

int len;

byte[] bytes = new byte[8 * 1024];

while ((len = bis.read(bytes)) != -1) {

bos.write(bytes, 0, len);

}

} catch (IOException e) {

e.printStackTrace();

}

// 记录结束时间

long end = System.currentTimeMillis();

System.out.println("缓冲流使用数组复制时间:" + (end - start) + " 毫秒");

}

}

缓冲流使用数组复制时间为 666 毫秒;

结论

缓冲流比传统的流效率更高,并且用数组的方式传输更快;


zhuanzhudeyipi
65 声望2 粉丝