Why is System.out.println so slow?

后端 未结 7 1301
情歌与酒
情歌与酒 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:48

    System.out is a static PrintStream class. PrintStream has, among other things, those methods you're probably quite familiar with, like print() and println() and such.

    It's not unique to Java that input and output operations take a long time. "long." printing or writing to a PrintStream takes a fraction of a second, but over 10 billion instances of this print can add up to quite a lot!

    This is why your "moving everything to a String" is the fastest. Your huge String is built, but you only print it once. Sure, it's a huge print, but you spend time on actually printing, not on the overhead associated with the print() or println().

    As Dvd Prd has mentioned, Strings are immutable. That means whenever you assign a new String to an old one but reusing references, you actually destroy the reference to the old String and create a reference to the new one. So you can make this whole operation go even faster by using the StringBuilder class, which is mutable. This will decrease the overhead associated with building that string you'll eventually print.

提交回复
热议问题