StringBuilder 如何大幅减少 Java 程序所需的时间?

How does a StringBuilder reduce time a Java program takes drastically?

有两个 Java 代码片段。在下方分享它们 -

1.

Collections.sort(al);
                Iterator<Integer> it = al.iterator();
                while(it.hasNext()){
                        sb.append(it.next());
                        sb.append("\n");
                }
                System.out.println(sb.toString());

2.

Collections.sort(al);
                Iterator<Integer> it = al.iterator();
                while(it.hasNext()){
                        System.out.println(it.next());
                }

分享以上程序所用的时间 - 1. 1.43 秒 2. 4.28秒

我想知道 StringBuilder 有什么神奇的作用,有人可以指导吗?

不是您的 StringBuilder 而是您的 System.out.println() 语句拖慢了执行时间。

速度慢是因为

Bytes had to be sent to the console application -> Each char has to be rendered using a true type font (cause for slow processing) -> Displayed area may have to be scrolled to append a new line to the visible area.