Sunday, March 31, 2013

Java Fast Input/Output





Most of the time I write my codes in Java,and its a bit frustrating to see that one cannot attain the speed of execution here compared to the other languages like C,Cpp. However, Java is very feature rich in terms of library support, user base and ease of OOP development.Due to its very organized and huge collection of library its often the programming language of choice for most professionals.

Java being an interpreted language is slower than C and other compiled language ,however it still can be optimized to the level where it can attain runtime speeds which varies from C by a factor of less than 2,and major optimization can be attained within the Input/Output section itself.

Often people use the Scanner class in Java for input(be it reading from a file or console),however Scanner is the slowest possible way of taking an input.

There are two other better class to achieve this :

1)BufferedReader
2)BufferedInputStream 

BufferedReader provides us with automated buffer management and also the very useful readLine() method(can take entire String of line as input,similar to Scanner's nextLine()) method.Often its sufficient when we deal with String inputs to use the buffered Reader class.
Given below is a small code snippet which demonstrates how to used the BufferedReader to take inputs as String.



BufferedInputStream is the fastest way to take Input,however we need to make our own buffer management and also there is no readLine() method predefined.

So,I am going to create  the following using BufferedInputStream.

  •  function readInt() //reads the next Integer skipping the newline and spaces
  •  function readLong() //reads the next Long skipping the newline and spaces
  •  function readString() //reads the next String till it gets a newLine("\n") 


Also,I have used the StringBuilder class here .StringBuffer is supposedly the fastest  way to build and manipulate Strings in java instead of the regular concatenation.However StringBuilder is not threadsafe, and for those of you who wants to use a threadsafe version can instead use the StringBuffer class.
Below I have embedded the code for the custom class I have created and added suitable comments.






No comments:

Post a Comment