用 Java 中的 long 作为键的映射

huangapple go评论76阅读模式
英文:

Map with long as key in Java

问题

我的性能分析器显示,我在很大一部分时间里将 long 包装成 Long,而我想避免这样做。我目前这样做是因为我使用了 Map<Long, V>。是否有一种常见的方法可以创建一个键为 long 的 Map 呢?

我知道它不会是 Map<long, V>,因为类型系统不允许这样做,但这并不意味着不能存在从 longV 的映射。实际上,这很容易实现,因为我只需要复制 HashMap<K,V> 的代码,将 K 替换为 long,并进行类型系统所需的所有更改(例如,键的迭代不再是 Iterator<K>)。

我的问题是是否已经存在这样的库,或者我应该自己动手实现?

背景是我的性能分析器显示,在进行批处理时,三分之一的时间用于将 long 转换为 Long,而没有任何理由为了类型系统而支付这个代价。

英文:

My profiler state I spend an important part of the time wrapping long into Long which I want to avoid. I currently do it because I use Map&lt;Long, V&gt;. Is there an usual way to create a Map whose keys are long ?

I know it won't be a Map&lt;long, V&gt; because the type system does not allow it, but that does not mean that a map from long to V can't exists. Actually, it would be quite easy to do, since I would just need to copy the code of HashMap&lt;K,V&gt;, replace K by long, and do all changes required by the type system (E.g. iteration over key would not be an Iterator&lt;K&gt; anymore)

My question is does such a library already exists, or should I do it myself ?

The context is that my profiler state that, when doing batch processing, a third of the time is spent transforming long into Long, and there is really no reason to accept to pay this price for the type system

答案1

得分: 1

http://fastutil.di.unimi.it/ 是一个完全符合我之前提问的库的类。

英文:

http://fastutil.di.unimi.it/ is a class of library doing exactly what I was asking for here

答案2

得分: 0

这是不受支持的,因为泛型不支持原始类型。你也不能创建一个包含原始类型的类(比如 HashMap&lt;int,V&gt;)。

也许JEP 218 - 原始类型上的泛型将在未来尝试解决这个问题。

建议:

  1. 你能否将代码的其余部分直接使用 Long 类型来代替?
  2. Long 类在范围 -127 到 128 内缓存数值(代码)。探索是否能够为更大范围的值实现类似的内部缓存。
英文:

This is not supported as generics does not support primitive types. You cannot create a class with primitive types as well (like HashMap&lt;int,V&gt;).

Maybe the JEP 218 - Generics over Primitive Types will look to solve this in the future.

Suggestions:

  1. Can you change the rest of the code to use a Long in the first place?
  2. The Long class caches values from -127 to 128 (code). Explore if you could have a similar internal cache for a bigger range.

huangapple
  • 本文由 发表于 2020年10月24日 16:48:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64511580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定