Search code examples
javaperformancevariablesconditional-statementsfinal

How condition variables work and store in memory in Java?


//Case1
if(a > 5){
    //..
}

//Case2
private static final int NUM1 = 5;
if(a > NUM1){
    //..
}

/////////////////////////////////////////////

//Case3
if(a > 6 + b){
    //..
}

//Case4
private static final int NUM2 = 6;
if(a > NUM2  + b){
    //..
}

In Java
1. How if condition's variables work in java? (for example: if(a > 5) how 5 is stored in memory? like final or else?)
2. should i use case2 instead of case1 for more performance?
3. should i use case4 instead of case3 for more performance?

for(int i = 0; i < 1000000000; i++){
    if(a > 5){}
    if(a > NUM){}
    if(a > 6 + b){}
    if(a > NUM  + b){}
}
  1. if i get into the loop, is result change?

Solution

  • I compiled code with these statements and disassembled.

    As you can see, there is no difference for comparisons between integer literals, and comparisons for public static final primitives.

    Curiously, on some JVMs the comparison (a>6+b) might be faster than (a>5), if bipush and iadd are more efficient than iconst. I'm personally not sure why bipush is used for cases 3 and 4 only. If someone could shed some light on this I would be interested.

    // method 1; if(a>5)
      13: iload_1
      14: iconst_5
      15: if_icmple     25
      18: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
      21: iconst_1
      22: invokevirtual #5                  // Method java/io/PrintStream.println:(I)V
    // method 2; if(a>NUM1)
      25: iload_1
      26: iconst_5
      27: if_icmple     37
      30: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
      33: iconst_2
      34: invokevirtual #5                  // Method java/io/PrintStream.println:(I)V
    // method 3; if(a > 6+b)
      37: iload_1
      38: bipush        6
      40: iload_2
      41: iadd
      42: if_icmple     52
      45: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
      48: iconst_1
      49: invokevirtual #5                  // Method java/io/PrintStream.println:(I)V
    // method 4; if(a > 6+b)
      52: iload_1
      53: bipush        6
      55: iload_2
      56: iadd
      57: if_icmple     67
      60: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
      63: iconst_1
      64: invokevirtual #5                  // Method java/io/PrintStream.println:(I)V
      67: return