Java - System.out effect on performance

后端 未结 5 2116
日久生厌
日久生厌 2020-12-09 05:49

I\'ve seen this question and it\'s somewhat similar. I would like to know if it really is a big factor that would affect the performance of my application. Here\'s my scenar

5条回答
  •  时光说笑
    2020-12-09 06:42

    I was recently testing with (reading and) writing large (1-1.5gb) text-files, and I found out that:

    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "UTF-8"), 512));
    out.println(yourString);
    //...
    out.flush();
    

    is in fact almost 250% faster than

    System.out.println(yourString);
    

    My test-program first read about 1gb of data, processed it a bit and outputted it in slightly different format.

    Test results (on Macbook Pro, with SSD reading&writing using same disk):

    • data-output-to-system-out > output.txt => 1min32sec
    • data-written-to-file-in-java => 37sec
    • data-written-to-buffered-writer-stdout > output.txt => 36sec

    I did try with multiple buffer sized between 256-10k but that didn't seem to matter.

    So keep in mind if you're creating unix command-line tools with Java where output is meant to be directed or piped to somewhere else, don't use System.out directly!

提交回复
热议问题