if else performance optimization

I’ve often heard that while using an if/else statement, it is often preferred to place the statement which is expected to be true more often in the if condition instead of the else condition. Well, today I did try this out and yes it is true.

void runIf(String varString) {
    if(varString.equals(“expected-to-be-true-more-often”)) {
        System.out.println(“test1”);
    } else {
        System.out.println(“test2”);        
    }

Now, call the function with varString = “expected-to-be-true-more-often”, about a 1000 times and note the time taken to execute the the method 1000 times. Then, call the same method with varString = “someOtherValue”, and note the time taken to execute the method a 1000 times.

I found that the time taken to run the more expected result was nearly half the value of the time taken to run the least expected result. (The ratio of the time taken in both cases may vary from system to system)

The result can be extended to the else if statement as well. The time taken to execute the else if statement will lie in the middle of the values of the time taken for if condition and the else condition.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: