Why is System.out.println so slow?

后端 未结 7 1297
情歌与酒
情歌与酒 2020-11-27 08:30

Is this something common to all programming languages? Doing multiple print followed by a println seems faster but moving everything to a string and just printing that seem

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 08:47

    println is not slow, it's the underlying PrintStream that is connected with the console, provided by the hosting operating system.

    You can check it yourself: compare dumping a large text file to the console with piping the same textfile into another file:

    cat largeTextFile.txt
    cat largeTextFile.txt > temp.txt
    

    Reading and writing are similiar and proportional to the size of the file (O(n)), the only difference is, that the destination is different (console compared to file). And that's basically the same with System.out.


    The underlying OS operation (displaying chars on a console window) is slow because

    1. The bytes have to be sent to the console application (should be quite fast)
    2. Each char has to be rendered using (usually) a true type font (that's pretty slow, switching off anti aliasing could improve performance, btw)
    3. The displayed area may have to be scrolled in order to append a new line to the visible area (best case: bit block transfer operation, worst case: re-rendering of the complete text area)

提交回复
热议问题