繁体   English   中英

如何在 java 中将 InputStream 转换为 Reader?

[英]How to convert InputStream to Reader in java?

  1. reader = new BufferedReader(new InputStreamReader(inputStream))
  2. reader = new InputStreamReader(new BufferedInputStream(inputStream))

哪个更好? 为什么?

解决方案 1 更有效。

BufferedReader 可以有比 InputStreamReader 更大的缓冲区。

此外,使用BufferedReader您可以使用方便的readline方法。

切勿在不提供编码的情况下创建Reader 正如@CodeScale 已经提到的,第一个选项更好,因为它更好地利用了BufferedReader并且它具有方便的方法。

   reader = new BufferedReader(new InputStreamReader(inputStream), StandardCharsets.UTF_8);

解决方案 1 更有效。

BufferedReader 将从 Reader 读取一个字符块(通常读入一个 char 数组)。 read() 方法将从内部数组返回数据。

基准测试显示第一种方式( reader = new BufferedReader(new InputStreamReader(inputStream)) )要快得多。

但我不知道为什么。

基准代码

package org.apache.commons.io.jmh;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
@Warmup(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS)
@Fork(value = 1, jvmArgs = {"-server"})
public class IOUtilsContentEqualsReadersBenchmark {
    private static final String TEST_PATH_16K_A = "/org/apache/commons/io/abitmorethan16k.txt";

    public static FileInputStream getInputStream() throws URISyntaxException, FileNotFoundException {
        return new FileInputStream(IOUtilsContentEqualsReadersBenchmark.class.getResource(TEST_PATH_16K_A).toURI().getPath());
    }

    @Benchmark
    public static void read1(Blackhole blackhole) throws Exception {
        Reader reader = new BufferedReader(new InputStreamReader(getInputStream()));
        while (true) {
            int res = reader.read();
            blackhole.consume(res);
            if (res == -1) {
                return;
            }
        }
    }

    @Benchmark
    public static void read2(Blackhole blackhole) throws Exception {
        Reader reader = new InputStreamReader(new BufferedInputStream(getInputStream()));
        while (true) {
            int res = reader.read();
            blackhole.consume(res);
            if (res == -1) {
                return;
            }
        }
    }

    @Benchmark
    public static void read3(Blackhole blackhole) throws Exception {
        Reader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(getInputStream())));
        while (true) {
            int res = reader.read();
            blackhole.consume(res);
            if (res == -1) {
                return;
            }
        }
    }
}

基准测试结果

[INFO] --- exec-maven-plugin:3.0.0:exec (benchmark) @ commons-io ---
# JMH version: 1.27
# VM version: JDK 1.8.0_275, OpenJDK 64-Bit Server VM, 25.275-b01
# VM invoker: C:\jdk8u275-b01\jre\bin\java.exe
# VM options: -server
# JMH blackhole mode: full blackhole + dont-inline hint
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read1

# Run progress: 0.00% complete, ETA 00:05:00
# Fork: 1 of 1
# Warmup Iteration   1: 141144.322 ns/op
# Warmup Iteration   2: 126969.546 ns/op
# Warmup Iteration   3: 117894.788 ns/op
# Warmup Iteration   4: 118555.020 ns/op
# Warmup Iteration   5: 117377.183 ns/op
Iteration   1: 118137.872 ns/op
Iteration   2: 117869.504 ns/op
Iteration   3: 117894.961 ns/op
Iteration   4: 118090.279 ns/op
Iteration   5: 117234.480 ns/op


Result "org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read1":
  117845.419 ��(99.9%) 1390.724 ns/op [Average]
  (min, avg, max) = (117234.480, 117845.419, 118137.872), stdev = 361.167
  CI (99.9%): [116454.695, 119236.143] (assumes normal distribution)


# JMH version: 1.27
# VM version: JDK 1.8.0_275, OpenJDK 64-Bit Server VM, 25.275-b01
# VM invoker: C:\jdk8u275-b01\jre\bin\java.exe
# VM options: -server
# JMH blackhole mode: full blackhole + dont-inline hint
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read2

# Run progress: 33.33% complete, ETA 00:03:20
# Fork: 1 of 1
# Warmup Iteration   1: 287001.406 ns/op
# Warmup Iteration   2: 269609.908 ns/op
# Warmup Iteration   3: 268606.597 ns/op
# Warmup Iteration   4: 259708.116 ns/op
# Warmup Iteration   5: 256359.254 ns/op
Iteration   1: 256837.341 ns/op
Iteration   2: 257773.909 ns/op
Iteration   3: 256669.369 ns/op
Iteration   4: 258031.384 ns/op
Iteration   5: 258269.111 ns/op


Result "org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read2":
  257516.223 ��(99.9%) 2774.519 ns/op [Average]
  (min, avg, max) = (256669.369, 257516.223, 258269.111), stdev = 720.534
  CI (99.9%): [254741.704, 260290.742] (assumes normal distribution)


# JMH version: 1.27
# VM version: JDK 1.8.0_275, OpenJDK 64-Bit Server VM, 25.275-b01
# VM invoker: C:\jdk8u275-b01\jre\bin\java.exe
# VM options: -server
# JMH blackhole mode: full blackhole + dont-inline hint
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read3

# Run progress: 66.67% complete, ETA 00:01:40
# Fork: 1 of 1
# Warmup Iteration   1: 146614.866 ns/op
# Warmup Iteration   2: 131029.887 ns/op
# Warmup Iteration   3: 120476.530 ns/op
# Warmup Iteration   4: 121140.296 ns/op
# Warmup Iteration   5: 119992.159 ns/op
Iteration   1: 120754.048 ns/op
Iteration   2: 120544.731 ns/op
Iteration   3: 120556.412 ns/op
Iteration   4: 120781.589 ns/op
Iteration   5: 120338.529 ns/op


Result "org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read3":
  120595.062 ��(99.9%) 693.931 ns/op [Average]
  (min, avg, max) = (120338.529, 120595.062, 120781.589), stdev = 180.212
  CI (99.9%): [119901.131, 121288.993] (assumes normal distribution)


# Run complete. Total time: 00:05:01

REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.

Benchmark                                   Mode  Cnt       Score      Error  Units
IOUtilsContentEqualsReadersBenchmark.read1  avgt    5  117845.419 �� 1390.724  ns/op
IOUtilsContentEqualsReadersBenchmark.read2  avgt    5  257516.223 �� 2774.519  ns/op
IOUtilsContentEqualsReadersBenchmark.read3  avgt    5  120595.062 ��  693.931  ns/op

Benchmark result is saved to target/jmh-result.org.apache.json

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM