File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Performance and the fly likes One if with multiple conditions, or nested ifs Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "One if with multiple conditions, or nested ifs" Watch "One if with multiple conditions, or nested ifs" New topic
Author

One if with multiple conditions, or nested ifs

Jussi Taimiaho
Ranch Hand

Joined: Mar 01, 2004
Posts: 40
I was just trying to figure out what are the conditions of one if-clause I wrote for one quick prototype. It's not that complex, but I thought it might be nicer for readability to have it in nested if -clauses. Is there any significant difference performance-wise?

Either

Or:


cheers,
Jussi
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I'd even bet that it will compile to the exact same byte code. You can test that using javap.

But even if not, I'm sure that for 99.999% of all cases the difference will be insignificant.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Simon Baker
Ranch Hand

Joined: Sep 09, 2004
Posts: 57
I'd be surprised if it didn't compile to the same byte code too.

Other points that may be relevant to Jussi (or others - forgive me if I'm teaching Grandma to suck eggs):

- The use of the shortcut logical operators (&&) motivates the above comment. If the alternative (&) were used all evaluations would happen regardless of the outcome of earlier tests, thus making the single "if" version logically different to the multiple "if" version.

- If the boolean tests themselves were more potentially time-consuming (e.g. executing a complex method) the order may become significant - generally putting time-consuming evaluations and/or those least likely to cause an end to execution of the "if" statement toward the end is better.

- As with all these things, when used in real application code if tests show the method containing this logic to be a performance problem test it, try different approaches, and test them rather than relying on what we may think likely. If tests show no problem don't worry about it.

Cheers,
Simon
[ January 10, 2007: Message edited by: Simon Baker ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: One if with multiple conditions, or nested ifs