将字节数组转换为输出流

时间:2018-08-18 18:29:55

标签: java

我有以下代码在Java程序中将字节数组写入OutputStream。

s

当缓冲区大小为770,000并且每个元素的最大长度为40时,此循环将花费2840毫秒。 有没有优化的方法可以更快地运行这些代码?

1 个答案:

答案 0 :(得分:1)

尽管用例还不是很清楚-什么是基础流,等等,但是在将输出流包装到一个缓冲流中的几个选项中,这似乎是有道理的,请参见以下简短示例。在FileOutputStream上,有40万个小型阵列,它的性能提高了20倍:

// Buffered write, time elapsed: 51
// Raw write, time elapsed: 1050

import java.io.*;
import java.util.*;


public class Test {
    public static void main(String [] args) throws Exception {
        int max = 400000;
        List<byte[]> arrays = new ArrayList<>(max);
        for(int i=0; i< max; i++) {
            arrays.add(new byte[40]);
        }

        try(FileOutputStream fout = new FileOutputStream("/tmp/deleteme")) {
            long start = System.currentTimeMillis();
            writeBuffered(arrays, fout);
            System.out.println("Buffered write, time elapsed: " + (System.currentTimeMillis() - start));
        }
        try(FileOutputStream fout = new FileOutputStream("/tmp/deleteme")) {
            long start = System.currentTimeMillis();
            writeRaw(arrays, fout);
            System.out.println("Raw write, time elapsed: " + (System.currentTimeMillis() - start));
        }
    }

    static void writeRaw(List<byte[]> arrays, OutputStream out) throws IOException {
        for (byte[] packet: arrays) {
            out.write(packet);
        }
    }

    static void writeBuffered(List<byte[]> arrays, OutputStream out) throws IOException {
        BufferedOutputStream bout = new BufferedOutputStream(out);
        for (byte[] packet: arrays) {
            bout.write(packet);
        }
    }
}