本文介绍了Java:if-return-if-return vs if-return-elseif-return的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

询问我的代码如下:

public boolean equals(Object obj)
{
    if (this == obj)
        return true;

    if (obj == null)
        return false;

    if (getClass() != obj.getClass())
        return false;

    // Check property values
}

我有一个声称这不是最优的评论,而是(如果我理解正确)它应该这样做:

I got a comment which claimed that this was not optimal, and that it instead (if I understood correctly) should do this:

public boolean equals(Object obj)
{
    if (this == obj)
        return true;

    else if (obj == null)
        return false;

    else if (getClass() != obj.getClass())
        return false;

    // Check property values
}

因为返回语句,我真的不明白为什么它们中的任何一个应该比另一个更高效或更快。鉴于某个对象,就我所见,这两种方法都必须进行相同数量的检查。并且由于返回语句,其中任何一个都不会运行额外的代码。

Because of the return statements, I can't really see why any of them should be more efficient or faster than the other. Given a certain object, both methods would have to do an equal number of checks as far as I can see. And because of the return statements, no extra code would run in any of them.

我在这里遗漏了什么吗?有东西吗?是否有一些编译器优化或正在进行的事情或其他什么?

Am I missing something here? Is there something to it? Are there some compiler optimizations or something going on or whatever?

我知道这是微优化,我很可能坚持第一种方式,因为我认为它看起来更干净,所有的ifs都在同一个位置。但我无能为力;我很好奇!

推荐答案

生成的字节代码对于这两种情况是相同的,所以这纯粹是一个问题风格。

The generated byte code is identical for those two cases, so it's purely a matter of style.

我制作了两种方法 e1 e2 并且都生成了这个字节代码(使用 javap -v 读取):

I produced two methods e1 and e2 and both produced this byte code (read using javap -v):


public boolean e1(java.lang.Object);
  Code:
   Stack=2, Locals=2, Args_size=2
   0:   aload_0
   1:   aload_1
   2:   if_acmpne   7
   5:   iconst_1
   6:   ireturn
   7:   aload_1
   8:   ifnonnull   13
   11:  iconst_0
   12:  ireturn
   13:  aload_0
   14:  invokevirtual   #25; //Method java/lang/Object.getClass:()Ljava/lang/Class;
   17:  aload_1
   18:  invokevirtual   #25; //Method java/lang/Object.getClass:()Ljava/lang/Class;
   21:  if_acmpeq   26
   24:  iconst_0
   25:  ireturn

我遗漏了代码I然后把它编成。

I left out the code I put after that to make it compile.

这篇关于Java:if-return-if-return vs if-return-elseif-return的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:52