Peter Kirk wrote:
I guess I could convert to an "enum" value and use that, or I could have
just used switch/case. My initial code was simply a really long if/else
construct.
Just to summarize the thread to date on this: Switching on an enum
*is* faster than switching on a string. (The compiler may use a vector
table; even if it just uses a series of comparisons, the comparisons
are cheaper.) However, converting the string to an enum more than
wipes out the dispatch gains, and is only worthwhile if you can use
the enum several times.
Now I have tried a dictionary of delegate methods. I really have no idea of
performance issues, but the code _appears_ cleaner in my class, due to the
fact that I don't have a huge if/else. I do however have a large constructor
where I initialise the dictionary... still, it was also the first time I
ever looked at delegates, so I consider it a learning experience.
I was thinking about this thread last night, and was going to suggest
a Dictionary.
For the three terms you initially showed, a Dictionary is probably
going to be slower than a switch - there's a certain amount of
overhead in computing commandString.GetHashCode() and traversing the
buckets. By fifteen terms, the Dictionary should be competitive, and
may even be faster; certainly the Dictionary will hold up better as
the app evolves and adds more commands.
Dictionary dispatch is much smaller and clearer than the big switch
statement. Of course, as you've found, you've simply moved the
complexity into the code that populates the Dictionary. However, you
can 'distribute' the code that populates the Dictionary, which reduces
the clutter and makes it easier to maintain as you add commands.
* If command handling is spread over multiple subsystems, you can have
each subsystem 'register' handlers when the subsystem is initialized.
That is, each subsystem's constructor would register its own
delegates.
* If all the command handling is done (or at least initiated) in
methods of the dispatching class, you can use custom attributes to
mark command handling methods. Instead of a long series of
`Dispatch["control"] = ControlHandler;` statements, you'd decorate the
ControlHandler method with an attribute like
`[CommandHandler("control")]`, and your Dictionary population code
would just look for methods with the CommandHandler attribute, and get
the command string from the attribute. The Dictionary population code
is more complex, but it's smaller and doesn't have to be modified when
you add a new command; you just add the command handler and the
attribute ensures registration.
--
..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.