Re: Using enums to avoid using switch/if
- From: "Karl Uppiano" <Karl_Uppiano@xxxxxxx>
- Date: Thu, 11 Jun 2009 06:18:58 GMT
"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.
.
- Follow-Ups:
- Re: Using enums to avoid using switch/if
- From: Karl Uppiano
- Re: Using enums to avoid using switch/if
- References:
- Using enums to avoid using switch/if
- From: aks_java
- Re: Using enums to avoid using switch/if
- From: Lew
- Re: Using enums to avoid using switch/if
- From: Wojtek
- Re: Using enums to avoid using switch/if
- From: Mayeul
- Re: Using enums to avoid using switch/if
- From: aks_java
- Re: Using enums to avoid using switch/if
- From: Mayeul
- Re: Using enums to avoid using switch/if
- From: Lew
- Re: Using enums to avoid using switch/if
- From: Mayeul
- Re: Using enums to avoid using switch/if
- From: Lew
- Using enums to avoid using switch/if
- Prev by Date: Re: What are the options for serializing a BufferedImage?
- Next by Date: Re: Using enums to avoid using switch/if
- Previous by thread: Re: Using enums to avoid using switch/if
- Next by thread: Re: Using enums to avoid using switch/if
- Index(es):
Relevant Pages
|