gpt4 book ai didi

java - 将字节数组转换为 OutputStream

转载 作者:行者123 更新时间:2023-11-30 10:12:22 25 4
gpt4 key购买 nike

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

public static void write(OutputStream out, ArrayList<byte[]> buffer) throws IOException {
for (byte[] packet: buffer) {
out.write(packet);
}
}

当缓冲区大小为 770,000 且每个元素的最大长度为 40 时,此循环需要 2840 毫秒。

是否有更优化/更快的转换方式?

最佳答案

虽然用例并不完全清楚——底层流是什么等等,但是在一些选项中,您将输出流包装到缓冲流中似乎很有意义,请看下面的一个简短示例。在 FileOutputStream 上,使用 400k 小数组,它提供了 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);
}
}
}

关于java - 将字节数组转换为 OutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51911504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com