关于自动装箱,Java 中 Map<Integer, Integer> 的有效替代方案?

Efficient alternative to Map<Integer, Integer> in Java, with regards to autoboxing?

我正在使用 LinkedHashMap<Integer, Integer> 来存储 2D 游戏中图块上的图层值。数字越大,数字越小。

在我的绘图函数中,我遍历值集并绘制每个值。这意味着我对值进行 (width * height * numLayers) 次拆箱。我打算移植到 Android,所以我想尽可能高效,但我觉得这太多了?

我使用 Map 的原因是层数(键)很重要:4 层以上的键绘制在玩家上方,等等。所以我经常需要跳过一堆键。

我可能只使用 int[10] 因为我不需要那么多层,但是与我当前的 HashMap 相比,所有未使用的层都将占用 32 位有密钥 0、9 并且只占用 64 位。

Efficient alternative to Map ?

SparseIntArraysHashMap<Integer,Integer> 更有效率。根据文档

SparseIntArrays map integers to integers. Unlike a normal array of integers, there can be gaps in the indices. It is intended to be more memory efficient than using a HashMap to map Integers to Integers, both because it avoids auto-boxing keys and values and its data structure doesn't rely on an extra entry object for each mapping. For containers holding up to hundreds of items, the performance difference is not significant, less than 50%.

更多参考click here

对于非Android语言

  • 编写您自己的基于哈希的映射 class(未实现 collections.Map)。在单元格数组中使用 'linear probe' 相对简单——另一种技术是链表,它(同样)将与 'direct array' 选项一样大。
  • GNU Trove has primitive maps 那会做你想做的。但是,如果您不想耗尽内存的每个字节,我会赞同 Thomas 的建议,只使用数组。