问题
A professor of mine once said that the following code should never be done:
System.out.println(object.toString());
He said (and I believe cited "Effective Java") it causes a double call. Since the print statement calls the toString method of an object, it would be less efficient to have the toString method called twice. The preferred method would be to just use:
System.out.println(object);
Obviously this way looks better in code and would save time. I will always do it like this no matter what, but my question is "Is this actually more EFFICIENT?". In looking through the PrintStream documentation, the print method has been overloaded to take a String as the parameter (which would be the case if the toString method were called first). I am not seeing where that version of the print method calls the toString method of the inputted parameter and I don't believe it would make sense for it to do that.
Also, sorry if this is a duplicate. I couldn't find any topics on it.
回答1:
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.
回答2:
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.
回答3:
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/
来源:https://stackoverflow.com/questions/16570937/tostring-method-within-system-out-println-a-double-call