Re: performance of short-circuit expression
On Mar 28, 8:07 am, "andrew_n...@yahoo.com" <andrew_n...@yahoo.com>
wrote:
I have lots of tests throughout my program which involve boolean and/
or expressions with several terms, which trigger an exception in one
case, otherwise, fall thru and execute code normally. Obviously the
exceptions are rare, but the boolean expressions are evaluated every
time.
My question is which is faster, the short-circuit && and || which
generate cascading if statements or the alternative & and | which
generate code without branches. Assume x86 architecture for example.
Also assume that normally the expression has either 2 or 3 boolean
terms (rarely 4 or more).
Obviously, it depends on the compiler, and the level of
optimization. Worrying about this sort of thing is counter
productive until the profiler tells you otherwise. There are
more important things to do with your time.
Note that the cases in question do not require short-circuits, either
is appropriate.
The reason I put this question to the newsgroup is that I do this
alot, and I was quite surprised in preliminary performance testing to
find that the short-circuit booleans were faster even when all of the
tests were being fired.
Why? It's what I'd na?vely expect if the tests return a boolean
result. The other forms are *not* boolean operators, so the
boolean result must be converted to an integral type. (I think
the modern 80x86 architecture has a single instruction to do
this, but back in the days of the 8086, you needed either a test
and a conditional branch, or some very tricky games with the
condition codes, and several instructions.)
Did I make a mistake somewhere? Aren't
branches kind of slow? This may seem like minutiae to some people,
but I would like to acquire a permanent habit that is performance
appropriate.
You're wasting your time. If your doing this as part of your
paid job, you're wasting your employers' money.
--
James Kanze (GABI Software) mailto:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]