1

This is similar to:

Printing to the console vs writing to a file (speed)

I was confused because there are two conflicting answers. I wrote a simple java program

 for(int i=0; i<1000000; i++){
       System.out.println(i);
 }

and ran it with /usr/bin/time -v java test to measure time to output to stdout, then I tried /usr/bin/time -v java test > file and /usr/bin/time -v java > /dev/null. Writing to console was slowest (10 seconds) then file (6 seconds) and /dev/null was fastest (2 seconds). Why?

Community
  • 1
  • 1
fo_x86
  • 2,583
  • 1
  • 30
  • 41

2 Answers2

5

Because writing to console needs to refresh the screen each time something is written, which takes time.

Writing to a file needs to write bytes on disk, which takes time, but less time than refreshing the screen.

And writing to /dev/null doesn't write anything anywhere, which takes much less time.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • +1 When you write lots of data to these output devices, it has to actually do something with the text and you program has to wait for it to do it. i.e. when the program is producing text too fast it is forced to slow down for the consumer. The device to read from/write to is often more important than what you do in Java. – Peter Lawrey Dec 17 '12 at 19:04
0

Another problem with System.out.println is that System.out by default is in autoflush mode, println practically switches off buffering. Try this

    PrintWriter a = new PrintWriter(System.out, false);
    for (int i = 0; i < 1000000; i++) {
        a.println(i);
    }
    a.flush();

and you will see that output to a file becomes ten times faster.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275