Aussie AI
Simple Case First
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Simple Case First
This method is similar to common case first — the idea is to test the simplest condition first. More complicated and time-consuming computations can be avoided if the first test succeeds (or fails, depending on the context). This idea appears in two main situations:
if-if
construct (nestedif
statements), and- logical operators (
&&
and||
).
The simplest test should be the first of a pair of nested if
statements and
should also be the first operand of a &&
or ||
operator.
In the examples below, the sub-expression “x!=0
” is evaluated first because it is the simplest and hence the least expensive
to evaluate.
This is the nested-if
example:
if (x != 0) { if (expensive_fn(x) != 0) { // ... } }
This is the &&
short-circuiting method:
if (x != 0 && expensive_fn(x) != 0) { // ... }
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |