Is Short-circuiting always a good idea?

  • Thread starter Thread starter Phil Jones
  • Start date Start date
P

Phil Jones

I'm just (as a matter of course) using AndAlso and OrElse statements to
short circuit checking, even for nominal things like Boolean comparisons.
I'm wondering, is that a good thing to do (for performance reasons) or is
there some hidden down-side to it.

I can see why it's good for say not checking an object ref if it doesn't
exist - I'm just wondering if it's a good habit to get into for everything.

Thanks for any insights.
===
Phil
 
I'm just (as a matter of course) using AndAlso and OrElse statements to
short circuit checking, even for nominal things like Boolean comparisons.
I'm wondering, is that a good thing to do (for performance reasons) or is
there some hidden down-side to it.

I can see why it's good for say not checking an object ref if it doesn't
exist - I'm just wondering if it's a good habit to get into for everything.

IMHO, it's a good habit for everything boolean. There's no downside. I
tend to think of AndAlso/OrElse as the boolean operators, while And/Or
are only for bitwise operations.

In fact, I can't remember the last time I used And/Or in a piece of
code.
 
Phil Jones said:
I'm just (as a matter of course) using AndAlso and OrElse statements to
short circuit checking, even for nominal things like Boolean comparisons.
I'm wondering, is that a good thing to do (for performance reasons) or is
there some hidden down-side to it.

I can see why it's good for say not checking an object ref if it doesn't
exist - I'm just wondering if it's a good habit to get into for everything.

Not only should you look into using short circuiting when you can, but
you must also place the operands in the proper order to gain the full
benefits from using short circuit evaluation.

Consider running this test every hour: (pseudo code)

If Now.Time = Noon AndAlso Now.Day = LeapDay Then ...

LeapDay (Feb 29) happens once every 4 years, but Noon happens once
each day. That means the second part (LeapDay) is tested at noon
every day, 365 days per year. for 4 years before the entire condition is
True.

But the reverse gains more benefit from the short circuit operator:

If Now.Day = LeapDay AndAlso Now.Time = Noon Then ...

In that siuation the second part is only tested 24 times, when LeapDay
has arrived.

That is an exaggerated situation, but it helps in pointing out that the
less frequent condition(s) need to be tested first, for optimal performance.

LFS
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top