What's the fastest way to output a string to system out?

前端 未结 5 1778
南旧
南旧 2020-12-04 22:58

I\'m doing something like this:

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

Basically, I compute an integer and out

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 23:32

    Keep in mind that I/O operations are very slow compared to in-memory processing (e.g. parsing of Integer). So, I would propose you to create the whole string 'in advance' and then print it out only once (of course if its possible):

    StringBuilder sb = new StringBuilder();

    for(int i = 0 ; i < 100000; i++) { sb.append(i).append("\n");}
    String printMe = sb.toString(); 
    System.out.println(printMe);
    

    There are various techniques like buffering the the level of output stream you're using, but I assume that you prefer to stay with the most basic System.out.println

    Hope this helps

提交回复
热议问题