Java – scanner and inputstreamreader

Does anyone happen to know the performance difference between the following two methods of reading input files?

1) Read files using scanner and file

Scanner input = new Scanner(new File("foo.txt"));

2) Reading files using inputstreamreader and FileInputStream

InputStreamReader input = new InputStreamReader(new FileInputStream("foo.txt"));

Solution

The first point is that none of these code examples read files This may sound crazy or incorrect, but it's true They actually open a file for reading In terms of what they actually do, their respective efficiency may not be very different

When it comes to actually reading a file, the best way to use it will depend on the content of the file, the memory algorithm of the data, and so on This will determine whether to better use the scanner or an original reader, from the perspective of performance, and more importantly, from the perspective of making your code reliable and maintainable

Finally, it is possible that this will not have a significant impact on the overall performance of your code What I'm talking about is that you optimize your application prematurely You now better ignore performance and choose a version that will make the rest of your code simpler When the application works normally, it is configured with some representative input data The analysis will tell you when to read the file with absolute data and when it relates to the rest of the application This will tell you if it's worth trying to optimize file reading

The only performance advice I give is that it is inefficient to read characters from unbuffered input streams or readers If you need to read the file in this way, you should add a BufferedReader to the stack

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>