Search code examples
javastringbuilder

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


Have two Java code snippets. Sharing them below -

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());
                }

Sharing the time the above programs took - 1. 1.43 seconds 2. 4.28 seconds

I wonder what magic StringBuilder does, can somebody guide?


Solution

  • It's not your StringBuilder but your System.out.println() statements which is slowing down the execution time.

    It is slow because

    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.