Presents your JAVA E-NEWSLETTER for November 14, 2002 <-------------------------------------------> IMPROVE PERFORMANCE WITH BUFFERED IO Java input/output (IO) performance can be increased by using the standard Buffered classes, just as the IO on your operating system improves its speed by buffering requests. For example, if a piece of code asks to read data off of a disk, it will potentially have that data in memory already. If the code wants to write some output to the disk, it may store it in memory for a while and wait for more data before completing the write. In Java's IO system, it is much faster to write a character to memory than it is to the disk, for example: // this block throws IOException Writer writer = new FileWriter( new File( "file.txt" ) ); for(int i=0; i<1000; i++) { writer.write(""+i); writer.write("\n"); } writer.close( ); In this sample code, the FileWriter will write the numbers out one at a time. Measuring elapsed time on an Apple Powerbook, the process took 180 milliseconds the first time, and 90 milliseconds thereafter, probably due to just-in-time compiling in the JVM. Adding buffering to the code is a simple case of building a BufferedWriter around the FileWriter: // this block throws IOException Writer writer = new BufferedWriter(new FileWriter( new File( "file.txt" ) ) ); for(int i=0; i<1000; i++) { writer.write(""+i); writer.write("\n"); } writer.close( ); Now the BufferedWriter will decide how often to send the write calls to the FileWriter. The flush( ) method may be used to force the write calls to be sent through. With the addition of the BufferedWriter, the code runs at around 63 milliseconds. The performance improvement of BufferedWriter under default conditions is particularly noticeable when lots of tiny outputs are being made. In addition to BufferedWriter, there is also a BufferedOutputStream with much the same qualities. On the input side there is a BufferedReader and a BufferedInputStream. It is important to note that the Buffered classes do not solely act upon file systems. Any Reader/Writer can be buffered to improve the speed of character input/output, and any OutputStream/InputStream can be buffered to improve the byte IO speed. ----------------------------------------