I have about 30 handler routines to dispatch when given a routine name, in String form.
So in a factory method, a natural way to dispatch routine is using a series of if...else to compare the routine name to fit in the slot. it works, but no doubt it is clumsy and inefficient as the number of routines rises up.
I came up with a fashion using enum and EnumMap: whenever I add a routine, I add an enum instance, and register it in EnumMap(the routine name and the routine class as key and value).
As what I know, when the number of instances is less than 64(the long type length), the EnumMap implementation uses a long as a bit array and use bit offset to do put and get, so it is extremely fast, and I could gain a O(1) performance when I dispatch the routine as long as the number of routine is less than 64(it quite suits for my situation).
However, a limit of EnumMap is that its key type can only be a Enum, instead of String,
and I could not use the routine name(string) to do a quick lookup….
Is there any way to work around this ?
Or if only I could do a reverse lookup using a value for a key 🙂
I would keep it simple and just use a
HashMap<String, Handler>until you can prove that this is a serious bottleneck. I’m assuming here that there’s a common superclass or interface that all your handlers extend, so you can just doEnumMap won’t be any faster if you’re starting from a String key as you first have to use
valueOfto get the enum value corresponding to the string, and this is itself implemented as a lookup in a HashMap…