简体   繁体   English

HashMap与数组在以下方法中的性能差异

[英]HashMap vs array performance difference in following approach

To solve Dynamic programming problem I used two approaches to store table entries, one using multi dimension array ex:tb[m][n][p][q] and other using hashmap and using indexes of 1st approach to make string to be used as key as in "m,n,p,q". 为了解决动态编程问题,我使用了两种方法来存储表条目,一种方法是使用多维数组ex:tb [m] [n] [p] [q],另一种方法是使用hashmap并使用第一种方法的索引来使要使用的字符串作为“ m,n,p,q”中的键。 But on one input first approach completes in 2 minutes while other takes more than 3 minutes. 但是,首先输入的一种方法在2分钟内完成,而另一种则需要3分钟以上。 If access time of both hashmap and array is asymptotically equal than why so big difference in performance ? 如果hashmap和array的访问时间渐近相等,那么为什么性能会有如此大的差异呢?

Like mentioned here : 这里提到的

HashMap uses an array underneath so it can never be faster than using an array correctly. HashMap使用下面的数组,因此它永远不会比正确使用数组快。

You are right, array's and HashMap's access time is in O(1) but this just says it is independent on input size or the current size of your collection. 没错,数组的访问和HashMap的访问时间在O(1)中,但这仅表示它与输入大小或集合的当前大小无关。 But it doesn't say anything about the actual work which has to be done for each action. 但这并没有说明每个动作必须完成的实际工作。

To access an entry of an array you have to calculate the memory address of your entry. 要访问阵列的条目,您必须计算条目的内存地址。 This is easy as array's memory address + (index * size of entity) . 这很容易,因为array's memory address + (index * size of entity)

To access an entry of a HashMap, you first have to hash the given key (which needs many cpu cycles), then access the entry of the HashMap's array using the hash which holds a list (depends on implementation details of the HashMap), and last you have to linear search the list for the correct entry (those lists are very short most of the time, so it is treated as O(1)). 要访问HashMap的条目,您首先必须对给定的键进行哈希处理(这需要很多cpu周期),然后使用包含列表的哈希(取决于HashMap的实现细节)来访问HashMap数组的条目。最后,您必须线性搜索列表中的正确条目(大多数情况下这些列表很短,因此将其视为O(1))。

So you see it is more like O(10) for arrays and O(5000) hash maps. 因此,您会发现它更像是数组的O(10)和O(5000)哈希映射。 Or more precise T(Array access) for arrays and T(hashing) + T(Array access) + T(linear search) for HashMaps with T(X) as actual time of action x . 或更精确的T(Array access)用于数组, T(hashing) + T(Array access) + T(linear search)用于HashMaps,其中T(X)作为实际动作时间x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM