问题
I am having difficulty comparing the two. So I am appealing to people with more detailed knowledge than me. I have to link a functional object to a name (String ... of course), and the function call is something like this:
serviceInstance.useThis(String name, Object parameter);
So far I am considering three options for the "backend" of this API:
- enum + EnumMap
- pure enum
- HashMap
1 and 2 are basically the same but 1 is in case I need to reuse the enum for other uses. My main concern boils down to how fast is the Enum.valueOf(String name) compared to the String.hashCode()?
here are the two implementations I am playing with:
public class HashMapHandlerType{
static HashMap<String, MyInterfaceProvider> handlers = ~ ;
public void useThis(String name, Object parameter) throws IllegalArgumentException {
MyInterfaceProvider prov = handlers.get(name);
if(prov != null){
prov.get().use(parameter);
}else{
throw new IllegalArgumentException(name);
}
}
}
public class EnumTypeHandler{
public void useThis(String name, Object parameter) throws IllegalArgumentException {
HandlersEnum.valueOf(name).get().use(parameter);
}
}
Advantages of Enum is not worrying about collisions in EnumMap if I wanted to use one. But is valueOf of Enum fast enough to win over String.hashCode() + dealing potential collisions in the hash function?
回答1:
When using valueOf it basically creates a map lazily. Also, on creation of the map it uses reflection to get the values. Since reflection calls are definitely expensive as compared to using String.hashCode() which in your case would have already been calculated.
回答2:
Louis Wasserman's comment answers the specific question. This is a more general answer to how to deal with this sort of question.
- Encapsulate the data structure and its access methods in a class, so that only that class's code depends on the design choice.
- Write the simplest, cleanest, most maintainable implementation option.
- Measure the program's performance.
- If it needs to be faster, profile.
- If the profile shows that methods associated with the data structure account for a significant fraction of the time, write and measure one or more alternative implementations. Pick the fastest.
This has two major advantages. If the question turns out not to matter, because the simplest implementation is fast enough, you don't waste any time on it. If the relative performance question does matter, you do the measurements in the context of your actual program, with real data.
来源:https://stackoverflow.com/questions/24254250/what-is-the-fastest-for-map-keys-enum-valueof-vs-string-hashcode