扫描仪与InputStreamReader [英] Scanner vs InputStreamReader

查看:155
本文介绍了扫描仪与InputStreamReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人碰巧知道下面两种读取输入文件的方法之间的性能是否存在差异?
谢谢。

Does anyone happen to know if there is any difference with regards to performance between the two methods of reading input file below? Thanks.

1)使用扫描仪和文件读取文件

1) Reading a file with Scanner and File

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

2)使用InputStreamReader和FileInputStream读取文件

2) Reading a file with InputStreamReader and FileInputStream

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


推荐答案

第一点是既不这些代码示例读取文件。这可能听起来很愚蠢或不正确,但确实如此。他们实际做的是打开一个文件进行阅读。就他们实际做的而言,他们各自的效率可能没有太大差异。

The first point is that neither of those code samples read a file. This may sound fatuous or incorrect, but it is true. What they actually do is open a file for reading. And in terms of what they actually do, there's probably not a huge difference in their respective efficiency.

当涉及到实际阅读文件时,最好的使用方法是取决于文件包含的内容,内存算法中数据的形式等等。这将决定使用扫描程序或原始数据是否更好从性能角度看 Reader ,从使代码可靠和可维护的角度来看,更重要的是

When it comes to actually reading the file, the best approach to use will depend on what the file contains, what form the data has to be in for your in-memory algorithms, etc. This will determine whether it is better to use Scanner or a raw Reader, from a performance perspective and more importantly from the perspective of making your code reliable and maintainable.

最后,这可能不会对代码的整体性能产生重大影响。我所说的是你过早地优化你的应用程序。您现在最好忽略性能并选择使其余代码更简单的版本。当应用程序正在运行时,请使用一些有代表性的输入数据对其进分析将告诉您读取文件所花费的时间,绝对值和相对于应用程序的其余部分。这将告诉您是否值得努力尝试优化文件读取。

Finally, the chances are that this won't make a significant difference to the overall performance of your code. What I'm saying is that you are optimizing your application prematurely. You are better of ignoring performance for now and choosing the version that will make the rest of your code simpler. When the application is working, profile it with some representative input data. The profiling will tell you the time is spent reading the file, in absolute terms, and relative to the rest of the application. This will tell you whether it is worth the effort to try to optimize the file reading.

我给出的唯一性能建议是从无缓冲的输入流或读取器读取字符的字符是低效的。如果需要以这种方式读取文件,则应该向堆栈添加BufferedReader。

The only bit of performance advice I'd give is that character by character reading from an unbuffered input stream or reader is inefficient. If the file needs to be read that way, you should add a BufferedReader to the stack.

这篇关于扫描仪与InputStreamReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆