Get faster console output (System.out.println() replacement)Tag(s): IO
If your program is doing a lot printing to the console using System.out.println() then it is possible to get a good performance boost by using an alternative to do the console output.
By default, System.out.print() is only line-buffered and does a lot work related to Unicode handling. Because of its small buffer size, System.out.println() is not well suited to handle many repetitive outputs in a batch mode. Each line is flushed right away. If your output is mainly ASCII-based then by removing the Unicode-related activities, the overall execution time will be better.
Consider this program :
import java.io.BufferedWriter;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
public class Test {
public static void main(String...args) throws Exception {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
System.out.print("abcdefghijk ");
System.out.print(String.valueOf(i));
System.out.print('\n');
}
System.err.println("Loop time: " +
(System.currentTimeMillis() - start));
}
}
>java Test >NUL Loop time: 7000
Now, rewrite this program to use a 512-bytes buffer and specify the ASCII as character-encoding to be used.
import java.io.BufferedWriter;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
public class Test {
public static void main(String...args) throws Exception {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512);
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
out.write("abcdefghijk ");
out.write(String.valueOf(i));
out.write('\n');
}
out.flush();
System.err.println("Loop time: " +
(System.currentTimeMillis() - start));
}
}
>java Test >NUL Loop time: 672
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com