You are probably not using enough buffering. If you write System.out, it will automatically clear each line, so grouping several lines together before writing can add some buffering. Better use the right buffer.
Using StringBuffer has the inherent cost of growing a buffer.
long start = System.nanoTime(); StringBuilder sb = new StringBuilder(); for(long i=0;i<50*1000;i++) sb.append("Hello World!\n"); System.out.print(sb); long time = System.nanoTime() - start; System.err.printf("Took %d ms%n", time/1000000);
prints
Took 30 ms.
However, on Linux, if you know that stdout is a file, you can write it directly.
long start = System.nanoTime(); String processId = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; FileOutputStream out = new FileOutputStream("/proc/" + processId + "/fd/1"); BufferedOutputStream bos = new BufferedOutputStream(out); final byte[] str = "Hello World!\n".getBytes(); for (long i = 0; i < 50 * 1000; i++) { bos.write(str); } bos.close(); long time = System.nanoTime() - start; System.err.printf("Took %d ms%n", time/1000000);
prints
Took 9 ms.
However, you need to be careful how much you optimize the code, as you may violate the implied rules of the standard and not accept it.;)
source share