Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

puzzled with java if else performance

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
like image 441
user1906966 Avatar asked Sep 06 '25 05:09

user1906966


1 Answers

Your test is bunk. If I swap the test conditions I get the exact opposite results:

1) performance 5891113
2) performance 15216601

2) performance 5428062
1) performance 15087676

It probably has to do with the JVM optimizing the code as the execution progresses. If I copy/paste the conditions a few times, I get this:

2) performance 6258694
1) performance 34484277
2) performance 978
1) performance 978
2) performance 908
like image 142
Diego Basch Avatar answered Sep 07 '25 20:09

Diego Basch