Why is BufferedReader read() much slower than readLine()?

后端 未结 6 799
不思量自难忘°
不思量自难忘° 2020-12-29 18:45

I need to read a file one character at a time and I\'m using the read() method from BufferedReader. *

I found that read() is a

6条回答
  •  梦谈多话
    2020-12-29 19:13

    Thanks @Voo for the correction. What I mentioned below is correct from FileReader#read() v/s BufferedReader#readLine() point of view BUT not correct from BufferedReader#read() v/s BufferedReader#readLine() point of view, so I have striked-out the answer.

    Using read() method on BufferedReader is not a good idea, it wouldn't cause you any harm but it certainly wastes the purpose of class.

    Whole purpose in life of BufferedReader is to reduce the i/o by buffering the content. You can read here in Java tutorials. You may also notice that read() method in BufferedReader is actually inherited from Reader while readLine() is BufferedReader's own method.

    If you want to use read() method then I would say you better use FileReader, which is meant for that purpose. You can read here in Java tutorials.

    So, I think answer to your question is very simple (without going into bench-marking and all that explainations) -

    • Each read() is handled by underlying OS and triggers disk access, network activity, or some other operation that is relatively expensive.
    • When you use readLine() then you save all these overheads, so readLine() will always be faster than read(), may not be substantially for small data but faster.

提交回复
热议问题