toString() method within System.out.println() a double call?

泪湿孤枕 提交于 2019-11-30 12:14:48

No, it is not more efficient -- precisely because of the overload that you mentioned. Moreover, a call of toString on a String is extremely quick, so even without an overload the difference would not be measurable.

However, your professor is right about not making the call like System.out.println(object.toString());, but the reason is different: since the call is unnecessary, the readers of your code may get confused.

Your examples call two different methods in PrintStream. Both call toString() at most once.

  • The first method calls println(String x), which does not call x.toString() itself.
  • The second method calls println( Object x ), which leads to a call of x.toString() if x is not null.

However, there is a potential advantage to using System.out.println(object). If object is null, this prints "null". The other statement throws a NullPointerException.

in a multithreading environment calling System.out.println is actually bad enough, even much worst than a unneeded call to toString. The "problem" exist because you have a synchorized call inside "println":

public void println() {
newLine();
}

private void newLine() {
try {
    synchronized (this) {
    ensureOpen();
...
}

So, if you are trying to write efficient java, you could start by avoiding it. As an alternative you could use any of the different logging mechanism, e.g. http://www.slf4j.org/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!