SparseArray vs HashMap

后端 未结 7 1694
-上瘾入骨i
-上瘾入骨i 2020-12-22 15:58

I can think of several reasons why HashMaps with integer keys are much better than SparseArrays:

  1. The Android documentation for a
7条回答
  •  臣服心动
    2020-12-22 16:26

    It's unfortunate that the compiler issues a warning. I guess HashMap has been way overused for storing items.

    SparseArrays have their place. Given they use a binary search algorithm to find a value in an array you have to consider what you are doing. Binary search is O(log n) while hash lookup is O(1). This doesn't necessarily mean that binary search is slower for a given set of data. However, as the number of entries grows, the power of the hash table takes over. Hence the comments where low number of entries can equal and possibly be better than using a HashMap.

    A HashMap is only as good as the hash and also can be impacted by load factor (I think in later versions they ignore the load factor so it can be better optimized). They also added a secondary hash to make sure the hash is good. Also the reason SparseArray works really well for relatively few entries (<100).

    I would suggest that if you need a hash table and want better memory usage for primitive integer (no auto boxing), etc., try out trove. (http://trove.starlight-systems.com - LGPL license). (No affiliation with trove, just like their library)

    With the simplified multi-dex building we have you don't even need to repackage trove for what you need. (trove has a lot of classes)

提交回复
热议问题