-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Leon,

On 4/22/16 12:24 PM, Leon Rosenberg wrote:
> Hi guys,
> 
> this is completely off-topic ;-)
> 
> I was wondering if using if/else is not actually slowing down your
> code. Lets say I have three possible conditions, A, B and C, which
> are exclusive. My native approach would be: if (A){...} if
> (B){...} if (C){...}
> 
> now some people would 'optimize' it as if (A){ ...} else if (B)
> {....} else if (C) { ....} and I think in the world of single-cpu
> computers this optimization could work.
> 
> But what is now, given that compilers can optimize stuff like this
> and tell the processor to calculate all 3 branches simultaneously,
> which is not possible for ifelse.
> 
> Which one would you choose? Equally important, which one do you
> think is more readable? I would say if else is hard to read, but
> this can be just personal impression.

I would always choose the case with the elses.

First, I think it's more clear: if you expect that only one branch of
the code will run, and no others, then the elses tell the reader that
fact without any further commentary. The zero-else case might help you
catch some logic errors (because for example you can log each entry
into a branch) but there are of course other ways to do that.

Second, it's more efficient, regardless of what type of processor you
have. Let's take an example where there are more than 3 branches. How
about something like a million branches (just to accentuate the
point)? If one of the branches runs, the others are skipped. If all
branches have an equal change of being chosen, then the CPU has to
perform on average 500000 predicates. If you put the common cases at
the top, you can do even better. Let's assume the 80/20 rule applies,
here, and you can take a guess that, on average, the CPU will only
have to perform 100000 predicates on average.

In Java (specifically), if you can use a switch statement, it's
(sometimes) even better: Java has bytecode primitives for two kinds of
switches: "lookup" switches and "table" switches. The first is just a
big table of possible predicate values and the addresses of the target
branch. The CPU scans through the (sorted) table of values and then
jumps based upon what it found. If you have a big table, this can be
less efficient than if/elseif/elseif. The second is even better: the
value of the predicate can be used to compute the location in the
table, so no scanning is required.

- -chris
-----BEGIN PGP SIGNATURE-----
Comment: GPGTools - http://gpgtools.org
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlceJg8ACgkQ9CaO5/Lv0PAODQCfRCBvVgM2HSM2/CBEGtlBe0Pg
MrcAn2OdBYKJR0OSApcBFfONJHOlKGY0
=YeMH
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscr...@tomcat.apache.org
For additional commands, e-mail: users-h...@tomcat.apache.org

Reply via email to