Map键最快的方法是什么:Enum.valueOf(〜)vs String.hashCode()? [英] What is the fastest for Map keys: Enum.valueOf(~) vs String.hashCode()?

查看:69
本文介绍了Map键最快的方法是什么:Enum.valueOf(〜)vs String.hashCode()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难比较两者。因此,我呼吁比我更详细的知识的人。
我必须将功能对象链接到名称(当然是字符串...),并且函数调用如下所示:

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);

到目前为止,我正在考虑此API后端的三个选项:

So far I am considering three options for the "backend" of this API:


  1. 枚举+ EnumMap

  2. 纯枚举

  3. HashMap

1和2基本相同,但如果我需要将枚举重用于其他用途,则使用1。
我的主要担心归结为Enum.valueOf(String name)与String.hashCode()相比有多快?

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);
    }

}

Enum的优点不用担心如果要使用EnumMap中发生冲突。
但是Enum的valueOf足够快以赢得String.hashCode()+处理哈希函数中的潜在冲突吗?

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?

推荐答案

使用valueOf时,它基本上会延迟创建地图。同样,在创建地图时,它使用反射来获取值。由于反射调用与使用String.hashCode()相比绝对昂贵,在您的情况下,String.hashCode()已被计算。

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.

这篇关于Map键最快的方法是什么:Enum.valueOf(〜)vs String.hashCode()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆