为什么EnumSet或EnumMap可能比散列的对手更有效率? [英] Why an EnumSet or an EnumMap is likely to be more performant than their hashed counterparts?

查看:176
本文介绍了为什么EnumSet或EnumMap可能比散列的对手更有效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容来自实施说明部分> EnumMap的Java文档

The following is from the Implementation Note section of Java doc of EnumMap :


实现注意事项:所有基本操作都在不间断的时间内执行。
他们很可能(但不能保证)比他们的
HashMap对手更快。

Implementation note: All basic operations execute in constant time. They are likely (though not guaranteed) to be faster than their HashMap counterparts.

我已经看到在$ doc文件中,类似于 EnumSet 的行。我想知道为什么更可能 EnumSets EnumMaps 将比其散列的对手更快?

I have seen a similar line in the java doc for EnumSet also . I want to know why is it more likely that EnumSets and EnumMaps will be more faster than their hashed counterparts ?

推荐答案

EnumSet 由位阵列支持。由于您可以提前知道您可以在 EnumSet 中输入的不同项目数量,我们可以为每个枚举值简单地保留一位。您可以设想 Set< Byte> Set< Short> 的类似优化,但对 Set< Integer> (您需要0.5 ^ GB的内存为2 ^ 32位)或一般。

EnumSet is backed by a bit array. Since the number of different items you can put in EnumSet is known in advance, we can simply reserve one bit for each enum value. You can imagine similar optimization for Set<Byte> or Set<Short>, but it's not feasible for Set<Integer> (you'd need 0.5 GiB of memory for 2^32 bits) or in general.

存在的操作 add ar constant time(就像 HashSet ),但是它们只需要检查或设置一个位。没有 hashCode()计算。这就是为什么 EnumSet 更快。还有更复杂的操作,如联合或使用位操作技术轻松实现。

Thus basic operations like exists or add ar constant time (just like HashSet) but they simply need to examine or set one bit. No hashCode() computation. This is why EnumSet is faster. Also more complex operations like union or easily implemented using bit manipulation techniques.

在OpenJDK中有两个 EnumSet RegularEnumSet 能够处理最多64个值的枚举 long JumboEnumSet 更大的枚举(使用 长[] )。但是这只是一个实现细节。

In OpenJDK there are two implementations of EnumSet: RegularEnumSet capable of handling enum with up to 64 values in long and JumboEnumSet for bigger enums (using long[]). But it's just an implementation detail.

EnumMap 的工作原理类似,但它使用对象[] 存储值,而密钥(索引)从 Enum.ordinal()隐式推断。

EnumMap works on similar principles, but it uses Object[] to store values while key (index) is implicitly inferred from Enum.ordinal().

这篇关于为什么EnumSet或EnumMap可能比散列的对手更有效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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