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

后端 未结 6 784
不思量自难忘°
不思量自难忘° 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:00

    Java JIT optimizes away empty loop bodies, so your loops actually look like this:

    while((c = fa.read()) != -1);
    

    and

    while((line = fa.readLine()) != null);
    

    I suggest you read up on benchmarking here and the optimization of the loops here.


    As to why the time taken differs:

    • Reason one (This only applies if the bodies of the loops contain code): In the first example, you're doing one operation per line, in the second, you're doing one per character. This this adds up the more lines/characters you have.

      while((c = fa.read()) != -1){
          //One operation per character.
      }
      
      while((line = fa.readLine()) != null){
          //One operation per line.
      }
      
    • Reason two: In the class BufferedReader, the method readLine() doesn't use read() behind the scenes - it uses its own code. The method readLine() does less operations per character to read a line, than it would take to read a line with the read() method - this is why readLine() is faster at reading an entire file.

    • Reason three: It takes more iterations to read each character, than it does to read each line (unless each character is on a new line); read() is called more times than readLine().

提交回复
热议问题