"Lew" <noone@lewscanon.com> wrote in message
news:h0pj4t$5ge$2@news.albasani.net...
Mayeul wrote:
As much as my seemingly-condescending* tone might make you think it was,
it wasn't my point. My point was that in the given example, replacing if
ladders with switch would buy little in terms of bloat, and that taking
advantage of enums is more likely to.
Looking at source code, switch statements are far more compact than if
ladders. Looking at run-time, switch statements typically use much
faster low-level instructions than a series of if statements, with less
impact on branch prediction.
You can use enums in place of if/switch in a state machine, where each
state is an enum. Each enum has an execute method that returns an enum for
the "next" state. The "next" state is determined by the current state and
possibly internal state variables. This helps eliminates the continual
checking of conditional logic to determine what to do next, which can have
a noticeable improvement on efficiency.
State state = State.BEGIN;
do {
state = state.execute();
} while (state != State.END);
The program logic is contained in the execute method for each enumerated
state. This is a great way for implementing things like parsers,
datastream decoders and scripting engines. Before enums came along, I used
classes, but the idea is about the same either way.
P.S. One might argue that "while (state != State.END)" is continually
checking conditional logic to determine what to do next. That's true, but
statements each iteration. You need *some* way to exit the loop. I suppose