• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

One if with multiple conditions, or nested ifs

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
reply
    Bookmark Topic Watch Topic
  • New Topic