Why is Scanner slower than BufferedReader when reading from input?

北慕城南 提交于 2019-11-28 12:05:39

Upper-level classes/methods are generally slower than lower-level classes/methods.
In the same way you could ask why is searching with regular expressions slower than
searching with String.indexOf(). Actually I've seen such questions here on SO.

The more specialized your class/method is, the better it can perform.
It does e.g. just 1 simple thing but does it quickly and efficiently.
More general classes/methods do e.g. 10-20 different things, so they
are more powerful but due to this they are slower.

I am speaking in general here, I haven't compared Scanner and BufferedReader myself.

Beside what has been already said Scanner focus is being a Swiss army knife, it is quite more complex and in simple cases covered by BufferedReader that extra gadgets burden it. It's like sending an aircraft carrier to kill a rat.

Scanner inbuilt functions parse the tokens where the BufferedReader just read the input.There is overhead of parsing tokens...

As mentioned in your question where you state a different question. The scanner performs extra tasks such as parsing integers and characters. The buffered reader reads raw input. What it reads is what it gives.

Hope I helped,

Jarod

Some highly voted hints why Scanner is slower can be found in Scanner vs. BufferedReader.

This performance difference may be critical in some cases like competitive programming. Therefore Codeforces has numerous posts with custom faster input parsers like here, here (with benchmark) and here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!