Problems with using System.out.println() in Java

Problems with using System.out.println() in Java

What is the problem?

Example - Java can find all primes up to 1 million in less than a second - but printing, and all of them on your own println, can take several minutes! Up to 10 billion hours to print!

That's huge !!!

What is System.out.println()

System: It is a final class defined in java.lang package

out: This is an instance of PrintStream type, which is a public and static member field of the System class

println(): It is a public method of PrintStream class which is invoked on out

image.png

About println() -

println() is a method that helps display output on the console. The message passed using println() is passed to the server’s console where kernel time is required to execute the task. Kernel time refers to the CPU time.

Since println() is a synchronized method, so when multiple threads are passed could lead to a low-performance issue. System.out.println() is a slow operation as it incurs heavy overhead on the machine compared to most IO operations.

Comparison with PrintWriter -

I compared the execution time of these two codes - one using System.out.println() and the other using PrintWriter. There is a visible difference in the execution time as n exceeds 10^3

image.png

image.png

Comparison Using Graphs -

Look at the graph to view the time difference in execution between System.out.println() and PrintWriter. As n increases System.out.println() takes a considerable amount of time.

image.png

image.png

Using StringBuilder -

We can create a StringBuilder and concatenate the output to it rather than using a println statement inside for loops. Look at the code below.

image.png

Conclusion

Therefore when println calls are huge we can either use StringBuilder or PrintWriter.

This is the end of the blog. Glad you liked.