File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

One if with multiple conditions, or nested ifs

 
Jussi Taimiaho
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Simon Baker
Ranch Hand
Posts: 57
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic