puzzled with java if else performance

Posted by user1906966 on Stack Overflow See other posts from Stack Overflow or by user1906966
Published on 2012-12-15T22:28:46Z Indexed on 2012/12/15 23:03 UTC
Read the original article Hit count: 333

Filed under:
|

I am doing an investigation on a method's performance and finally identified the overhead was caused by the "else" portion of the if else statement. I have written a small program to illustrate the performance difference even when the else portion of the code never gets executed:

public class TestIfPerf
{
    public static void main( String[] args )
    {   
        boolean condition = true; 
        long time = 0L;
        int value = 0;
        // warm up test 
        for( int count=0; count<10000000; count++ )
        {       
            if ( condition ) 
            {           
                value = 1 + 2;  
            }           
            else        
            {           
                value = 1 + 3;  
            }           
        }       
        // benchmark if condition only
        time = System.nanoTime();
        for( int count=0; count<10000000; count++ )
        {
            if ( condition )
            {
                value = 1 + 2;
            }           
        }
        time = System.nanoTime() - time; 
        System.out.println( "1) performance " + time ); 
        time = System.nanoTime();
        // benchmark if else condition
        for( int count=0; count<10000000; count++ )
        {
            if ( condition )
            {
                value = 1 + 2;
            }           
            else
            {
                value = 1 + 3;
            }
        }
        time = System.nanoTime() - time; 
        System.out.println( "2) performance " + time ); 
    }   
}

and run the test program with java -classpath . -Dmx=800m -Dms=800m TestIfPerf.

I performed this on both Mac and Linux Java with 1.6 latest build. Consistently the first benchmark, without the else is much faster than the second benchmark with the else section even though the code is structured such that the else portion is never executed because of the condition. I understand that to some, the difference might not be significant but the relative performance difference is large. I wonder if anyone has any insight to this (or maybe there is something I did incorrectly).


Linux benchmark (in nano)

  1. performance 1215488
  2. performance 2629531

Mac benchmark (in nano)

  1. performance 1667000
  2. performance 4208000

© Stack Overflow or respective owner

Related posts about java

Related posts about Performance