Tuesday, August 15, 2006

Java IO

BufferedReader saves your memory!

In Java, input with Scanner (1.5) is very slow, and requires more memory. Scanner tries to read all data when initialized. However, Scanner is a convenient with methods like nextInt, and self defined delimiters.

BufferedReader is not as convenient but more efficient. Use StringTokenizer to extract numbers from a line if needed.

Generally speaking, Java IO is slower and requires more memory than other common languages.

Some tips on Java IO

  • Scanner is suitable to read input data for the most of problems, but it is very slow. You should use it to read small input data only.


  • BufferedReader provides quite fast read operations for almost all problems. But this class may be used to read single characters and lines only. To read tokens and numbers you should use StringTokenizer or StreamTokenizer.


  • PrintWriter is preferred in all cases and works rather fast. But its method printf is too slow as well as calls like println(a + " " + b). You should output variables one-by-one to reach the highest performance.



No comments:

Post a Comment

Please post your comment here. ;)