Java Performance Tips 1

Java Performance Tips 1

12. I/O Streams

The best performance can be achieved by chaining the streams. The following code gives file copying using low level byte streams FileInputStream and FileOutputStream.

The above code takes around 1500 milliseconds to copy a source file of around 1.5 lakhs bytes. To increase the performance, chaining is done as in the following program.

12.1 Using Chaining (Buffering)

The FileInputStream is chained with BufferedInputStream as in the following code.

Chaining with Buffered streams increases a lot of performance and the time taken is just only 15 milliseconds compared to 1500 milliseconds of the previous code.

13. Formatting

We have seen reading data and how to increase the performance. Now, we will see the performance costs of converting data into different formats. Formatting costs relate to arranging characters in desired style and writing the formats to disk storage.

Different formats are used, in the following program where the same number is squared.

Output screen of

In fact using message format is too slower than without using format patterns. Message formats can be used for internationalization of the applications and at the same time performance overhead is thought.

14. Getting File Information(Disk access)

Always disk access is very expensive because a language has to communicate with the underlying operating system. Disk access may be required to get the file information like size, reading and writing permissions, to know a directory or a file etc. Sometimes it may be required to know the size of the file, and at the same time, assign the value to a variable in the program. If required again, we can use the same variable without accessing again.

The length() does not get the size of the file directly. In turn, the JVM uses a system call to get the size of the file. Such system calls are comparatively expensive. One simple way is to avoid querying the same information twice(of course, the file size not getting changed).

5 thoughts on “Java Performance Tips 1

Leave a Reply

Your email address will not be published. Required fields are marked *