Scanner vs InputStreamReader

前端 未结 3 970
迷失自我
迷失自我 2020-12-29 08:53

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) Reading a file wit

3条回答
  •  囚心锁ツ
    2020-12-29 09:42

    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.

    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.

    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.

提交回复
热议问题