Performance difference this two technique of console output?

I was solving one question based on printing pattern in which I had to perform lot of output stuff.I used to approach for this which are as follows:-

APPROACH-1

I used System.out.println() statement for printing every single character on the screen.

APPROACH-2

In this approach I appended every single character to a StringBuilder and then output that on screen using same System.out.println() statement.

When I used first approach I got TLE then after seeing someone else’s solution I used the second approach and got sufficiently higher performance, which not only pulled me out of TLE but also brought down my execution to the great extent.

Can anyone explain me the reason why there is such a performance difference in the two approaches.

@arpit728 This is because System.out.println() flushes the output every time it is called, that’s why it increases the running time of program, and it’s a good habit to use StringBuilder so that you need to output once per test case. In StringBuilder it is not necessary to create new instance every time, after printing the output you can clear the data using method setLength(0).

1 Like

@arpit728 the answer provided by @srd091 is correct. However I just want to mention here that there is an alternative to using a StringBuffer which I prefer. You can wrap the standard output stream with a PrintWriter without autoflush to achieve the same result.

PrintWriter pw = new PrintWriter(System.out); //by default autoflush is off
pw.println("Hello, World!");
...
...
pw.flush(); //or pw.close() at the end of the program to flush the buffer 

So the only changes to what you’re used to doing is

  1. Making a PrintWriter object at the beginning
  2. Replacing all System.out.println() statements with pw.println()
  3. Adding a pw.flush() at the end of the program

This actually requires less typing if you make a personal template which you copy and use for every program :wink:

@srd091

I got you. What I did is I created the new instance of stringBuilder for every test case. wouldn’t calling setLength(0) be overkill.

1 Like

@arpit728 Yes, you don’t need to create new instance for every test case. Instead of creating new instance for every test case you can create it once and then use setLength method to clear data at the end of each test case.