首页 > 解决方案 > 序列输入流比文件输入流快吗

问题描述

我想知道哪个更快。序列输入流或文件输入流。这是我的示例程序

FileInputStream fileInput = new FileInputStream("C:\\Eclipse\\File Output Stream.txt");
FileInputStream fileInput1=new FileInputStream("C:\\Eclipse\\Buffer Output Stream.txt");
SequenceInputStream sequence=new SequenceInputStream(fileInput,fileInput1);
FileOutputStream outputSequenceStream=new FileOutputStream("C:\\Eclipse\\File OutputSequence Stream.txt");
int i=0;
byte[] b = new byte[10];
long start=System.currentTimeMillis();
//System.out.println(start);
while((i=sequence.read())!=-1){
    //outputSequenceStream.write(i);
    System.out.println(Integer.toBinaryString(i)+"  "+i+"  "+ (char)i);
}
System.out.println(System.currentTimeMillis()-start);
System.out.println("success");
System.out.println("Reading one file after another using file input");

FileInputStream fileInput2 = new FileInputStream("C:\\Eclipse\\File Output Stream.txt");
FileInputStream fileInput3=new FileInputStream("C:\\Eclipse\\Buffer Output Stream.txt");
start=System.currentTimeMillis();
/* Reading first file */
while((i=fileInput2.read())!=-1){
    System.out.println((char)i);
}
/* Reading second file */
while((i=fileInput3.read())!=-1){
    System.out.println((char)i);
}
System.out.println(System.currentTimeMillis()-start);
System.out.println("Success");

文件输入流给我的数字比序列输出流少。这是否意味着序列比文件输入流慢。如果是这样,那么为什么我们使用序列流而不是使用文件输入流会更好?

标签: javafilestream

解决方案


javadoc 非常清楚该类的用途:

SequenceInputStream 表示其他输入流的逻辑串联。它从输入流的有序集合开始,从第一个读取直到到达文件末尾,然后从第二个读取,依此类推,直到最后一个包含的输入流到达文件末尾。

只是一种抽象,允许您轻松“连接”多个输入源。

它根本不应该影响性能,从这个意义上说,这里的“真正”答案是学习如何正确地对 java 代码进行基准测试。初学者请看这里

最重要的是,您还忘记了操作系统。为了真正衡量 IO 性能,您应该使用不同的文件(以避免操作系统首先将内容读取到内存中,然后所有后续读取都进入内存!)您还必须使用可能包含 100 MB 数据的文件,而不是 10位。

换句话说:您的数字毫无意义,因此无法从中得出任何结论。


推荐阅读