简体   繁体   English

HashMap与ArrayList插入性能的混淆

[英]HashMap vs. ArrayList insertion performance confusion

根据我的理解,哈希表插入为O(1),对于数组列表,插入为O(n),因为对于哈希表,哈希函数会计算哈希码和索引并插入条目,并且每次输入新数组时,数组列表都会进行比较元件。

Firstly, an operation of complexity O(1) does not always take lesser time than an operation of complexity O(n). 首先,复杂度为O(1)的操作并不总是比复杂度为O(n)的操作花费更少的时间。 O(1) only means that the operation takes a constant time (which could be any value), regardless of the size of the input. O(1)仅表示该操作花费一个恒定时间(可以是任何值),而不管输入的大小如何。 O(n) means that the time required for the operation increases linearly with the size of the input. O(n)表示操作所需的时间随着输入大小的增加而线性增加。 This means that O(1) is theoretically guaranteed to take lesser time than O(n) only when n is infinity. 这意味着从理论上讲,只有当n为无穷大时,O(1)才会比O(n)花费更少的时间。

Now coming to your examples, ArrayList.add() operation runs in amortized constant time, which means although it could take up to O(n) time for a particular iteration, the average complexity spread out over time is O(1). 现在来看您的示例, ArrayList.add()操作以摊销的恒定时间运行,这意味着尽管特定迭代可能要花费O(n)时间,但随时间分布的平均复杂度为O(1)。 For more information on amortized constant time, refer to this question. 有关摊销固定时间的更多信息,请参阅问题。

ArrayList is faster than the HashMap when you add item at the last of the ArrayList because there is no need to shift the elements in the ArrayList to the right side, you can see the efficiency of the HashMap if you add an item at the front of the ArrayList like this arrayList.add(0, str) . 当您在ArrayList的最后添加项目时, ArrayListHashMap快,因为不需要将ArrayList的元素移到右侧,如果您在HashMap的前面添加项目,则可以看到HashMap的效率。所述ArrayList这样arrayList.add(0, str)

when check this use 1000 as outer loop instead of 100000 otherwise it may hang. 检查时,请使用1000作为外循环,而不是100000否则可能会挂起。

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

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