Cost of compound if/or versus try/catch in Java 6

后端 未结 7 1650
旧时难觅i
旧时难觅i 2020-12-31 20:12

We currently have the following compound if statement...

if ((billingRemoteService == null)
    || billingRemoteService.getServiceHeader() == null
    || !\"         


        
7条回答
  •  星月不相逢
    2020-12-31 20:38

    OK, none of the answers really answered the question, though theZ's suggestion was the fastest way to check this given my current circumstances. None of this code was designed or written by me, and the application it is part of is massive, which would mean person-years of refactoring to handle every situation like this.

    So, for everyone's edification:

    I whipped up a quick test that mocks the classes required for both methods. I don't care how long any of the individual methods of the classes run, as it is irrelevant to my question. I also built/ran with JDKs 1.6 and 1.7. There was virtually no difference between the two JDKs.

    If things work --- IE no nulls anywhere, the average times are:

    Method A (compound IF):  4ms
    Method B (exceptions):   2ms
    

    So using exceptions when objects are not null is twice as fast as a compound IF.

    Things get even more interesting if I deliberately force a null pointer exception at the get(0) statement.

    The averages here are:

    Method A: 36ms
    Method B:  6ms
    

    So, it's clear that in the original case documented, exceptions are the way to go, cost-wise.

提交回复
热议问题