我应该缓冲InputStream还是InputStreamReader?

我应该缓冲InputStream还是InputStreamReader?,第1张

我应该缓冲InputStream还是InputStreamReader?

r1
更有效率。在
InputStreamReader
本身不具备大的缓冲。所述
BufferedReader
可以被设置为具有比较大的缓冲区
InputStreamReader
。将
InputStreamReader
r2
将作为一个瓶颈。

简而言之:您应该通过漏斗而不是瓶子读取数据。


更新 :这是一个小基准程序,只需复制“粘贴”即可运行它。您不需要准备文件。

package com.stackoverflow.q3459127;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.Reader;public class Test {    public static void main(String... args) throws Exception {        // Init.        int bufferSize = 10240; // 10KB.        int fileSize = 100 * 1024 * 1024; // 100MB.        File file = new File("/temp.txt");        // Create file (it's also a good JVM warmup).        System.out.print("Creating file .. ");        BufferedWriter writer = null;        try { writer = new BufferedWriter(new FileWriter(file)); for (int i = 0; i < fileSize; i++) {     writer.write("0"); } System.out.printf("finished, file size: %d MB.%n", file.length() / 1024 / 1024);        } finally { if (writer != null) try { writer.close(); } catch (IOException ignore) {}        }        // Read through funnel.        System.out.print("Reading through funnel .. ");        Reader r1 = null;     try { r1 = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"), bufferSize); long st = System.nanoTime(); for (int data; (data = r1.read()) > -1;); long et = System.nanoTime(); System.out.printf("finished in %d ms.%n", (et - st) / 1000000);        } finally { if (r1 != null) try { r1.close(); } catch (IOException ignore) {}        }        // Read through bottle.        System.out.print("Reading through bottle .. ");        Reader r2 = null;     try { r2 = new InputStreamReader(new BufferedInputStream(new FileInputStream(file), bufferSize), "UTF-8"); long st = System.nanoTime(); for (int data; (data = r2.read()) > -1;); long et = System.nanoTime(); System.out.printf("finished in %d ms.%n", (et - st) / 1000000);        } finally { if (r2 != null) try { r2.close(); } catch (IOException ignore) {}        }        // Cleanup.        if (!file.delete()) System.err.printf("Oops, failed to delete %s. Cleanup yourself.%n", file.getAbsolutePath());    }}

使用Seagate Momentus
7200.3
硬盘在Latitude
E5500上的结果:

创建文件..完成,文件大小:99 MB。在1593毫秒内完成了通过渠道的读取 *** 作。读完瓶子..完成了7760毫秒。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5096073.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存