Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does System.out.println() effect the code efficiency ?

Tags:

java

I used to write & develop codes with system.out.println(). it usually helps me track values and where the problem is coming. And after developed application, I don't remove the system.out.println() because it might helpful after user found any issue it will come back to us, which makes it so easy to track where went to wrong. But one of my superior suggested to remove system.out.println() from codes because its effect the code efficient level. Is this correct?

From my point of view, System.out.print() hardly take bytes on memory, so is it true that developer shouldn't use much system.out.println ??

Thanks in advance.

like image 760
Will Mcavoy Avatar asked May 28 '13 05:05

Will Mcavoy


People also ask

What is the purpose of system out Println () method?

out. println(): This method prints the text on the console and the cursor remains at the start of the next line at the console.

What is true about system out Println and system out print?

The only difference between println() and print() method is that println() throws the cursor to the next line after printing the desired result whereas print() method keeps the cursor on the same line. print() method. println() method.

How do I make system out Println faster?

Just type syserr and press ctrl + space, it will generate System. err. println statement and place the cursor in right place to type message.


2 Answers

System.out implementation contains a synchronized block on the output stream.

From PrintStream.java :

      /**
        * Prints a String and then terminate the line.  This method behaves as
        * though it invokes <code>{@link #print(String)}</code> and then
        * <code>{@link #println()}</code>.
        *
        * @param x  The <code>String</code> to be printed.
        */

       public void println(String x) {
           synchronized (this) {
               print(x);
               newLine();
           }
      }

Putting System.out.println a lot will make the entire project to run almost single-threaded, because all thread will waiting for synchronization lock, and make your application begin to crawl.

This means your superior is right.

Alternatively, Use logging framework like log4j instead. You can still configure your log4j to still output to System.out.println by just minor changes in the appender configuration.

like image 100
Rudy Avatar answered Sep 29 '22 12:09

Rudy


use of logging frameworks such as SLF4J is highly recommended. That way by configuration, you can execute these logging statements based on the environement.

eg - DEBUG level on Developer -- WARN on Production, so only critical iformation is logged in production.

like image 25
Sanath Avatar answered Sep 29 '22 12:09

Sanath