System.out.println()内的toString()方法是双重调用? [英] toString() method within System.out.println() a double call?

查看:276
本文介绍了System.out.println()内的toString()方法是双重调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一位教授曾说过以下代码永远不应该完成:

A professor of mine once said that the following code should never be done:


System.out.println(object.toString( ));

System.out.println(object.toString());

他说(我相信引用Effective Java)会导致双重调用。由于print语句调用对象的toString方法,因此将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);

System.out.println(object);

显然,这种方式在代码中看起来更好,可以节省时间。无论怎样,我总会这样做,但我的问题是这实际上更有效吗?。在查看 PrintStream 文档时, print方法已被重载以获取String作为参数(如果首先调用toString方法,则会出现这种情况)。我没有看到该版本的print方法调用输入参数的toString方法,我不相信它会这样做有意义。

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.

推荐答案

不,它效率不高 - 正是因为过载你提到过。此外,在 String 上调用 toString 非常快,所以即使没有重载,差异也无法衡量。

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.

但是,你的教授是不是像 System.out.println(object.toString()); ,但原因不同:由于调用是不必要的,代码的读者可能会感到困惑。

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.

这篇关于System.out.println()内的toString()方法是双重调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆