Re: Using enums to avoid using switch/if




"Lew" <noone@xxxxxxxxxxxxx> wrote in message news:h0pj4t$5ge$2@xxxxxxxxxxxxxxxxxxxx
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.

.



Relevant Pages

  • Re: Using enums to avoid using switch/if
    ... 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 run-time, switch statements typically use much faster low-level instructions than a series of if statements, with less impact on branch prediction. ... Each enum has an execute method that returns an enum for the "next" state. ...
    (comp.lang.java.programmer)
  • Re: Enum, switch, and a null
    ... your enum to replace switch branches. ... Wojtek :-) ... 100's of switch statements. ... Perhaps using enum isn't exactly what you intended. ...
    (comp.lang.java.programmer)
  • Re: Using enums to avoid using switch/if
    ... 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 run-time, switch statements typically use much faster low-level instructions than a series of if statements, with less impact on branch prediction. ...
    (comp.lang.java.programmer)
  • Re: enum and switch
    ... Daniel Pitts wrote: ... designed OO programs tend NOT to have switch statements. ... Don't put any logic into an enum, ...
    (comp.lang.java.programmer)
  • Re: shame on MISRA
    ... to be used as a switch argument. ... enum integer ... case zero: ... I also regularly write switch statements that are using ...
    (comp.arch.embedded)