System.out.println()是否会影响代码效率?

Wil*_*voy 14 java

我过去常常编写和开发代码system.out.println().它通常可以帮助我跟踪价值和问题的来源.在开发应用程序之后,我不会删除system.out.println()它,因为它可能会有用,因为用户发现任何问题它会回复给我们,这使得它很容易跟踪哪里出错.但我的一位上级建议system.out.println()从代码中删除,因为它影响代码的效率水平.它是否正确?

从我的角度来看,System.out.print()几乎不占用内存字节,因此开发人员不应该使用多少system.out.println

提前致谢.

Rud*_*udy 19

System.out实现包含输出流上的synchronized块.

来自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();
           }
      }
Run Code Online (Sandbox Code Playgroud)

大量放入System.out.println将使整个项目几乎单线程运行,因为所有线程都将等待同步锁定,并使您的应用程序开始爬行.

这意味着你的上司是对的.

或者,使用日志框架log4j代替.您仍然可以通过appender配置中的微小更改将log4j配置为仍然输出到System.out.println.