简体   繁体   English

Java中“if”条件的奇怪优化

[英]Strange optimization of “if” conditions in Java

I have decided to check the Java Compiler's perspicacity; 我决定检查Java编译器的明显性; thus, I have written a simple class. 因此,我写了一个简单的课程。

public class Foo {
    public Foo(boolean a, int b) {
        if (a == true && a != false) {
            b = 1;
        }
    }
}

I was wondering whether the compiler will optimize the condition to something simpler like: 我想知道编译器是否会将条件优化为更简单的条件:

if (a == true) {}

I compiled the class and then disassembled it with the javap tool. 我编译了该类,然后使用javap工具对其进行了反汇编。 When I took a look at the output, I was truly dumbfounded, because the compiler checks both of these conditions, what is clearly shown below. 当我看一下输出时,我真是傻眼了,因为编译器检查了这两个条件,下面清楚地显示了什么。

Compiled from "Foo.java"
public class Foo {
  public Foo(boolean, int);
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: iload_1
       5: iconst_1
       6: if_icmpne     15
       9: iload_1
      10: ifeq          15
      13: iconst_1
      14: istore_2
      15: return
}

I am just curious, why is it executing redundant instructions, when it can be optimized to something simpler? 我只是好奇,为什么它可以执行冗余指令,什么时候可以优化到更简单的东西?

The javac does no or only little optimization. javac没有或只有很少的优化。 The optimization occures during just-in-time (JIT) compilation of the bytecode. 在字节码的即时(JIT)编译期间发生优化。 This makes sense, because with this approach you can optimize differently for different target platforms and gain maximum optimization results. 这是有道理的,因为使用此方法,您可以针对不同的目标平台进行不同的优化,并获得最大的优化结

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM