【问题标题】:Performance of LinkedHashMap: Big O, Memory cost, etcLinkedHashMap的性能:大O、内存开销等
【发布时间】:2020-07-25 15:28:26
【问题描述】:

这是一个新手问题:LinkedHashMap 的 get/put/contains 的大 O 是什么?据我了解,对于 TreeMap,它是 O(logN),对于 LinkedList(按值搜索/添加/删除),它是 O(N)。这会使 LinkedHashMap 在 O(logN) 上运行,还是表现更好?以及在性能和内存使用等方面与 HashMap 相比如何?

【问题讨论】:

    标签: java algorithm linkedhashmap


    【解决方案1】:

    LinkedHashMap 提供与 HashMap 类似的性能(就大 O 表示法而言),但也允许按插入顺序进行确定性迭代。

    这意味着,get()put()contains() 都在O(1) 中完成(摊销平均)。

    您可以在documentation阅读更多内容。

    【讨论】:

      【解决方案2】:

      所有 3 次都是O(1)。换句话说,时间与数据集大小无关。内存是O(N)

      【讨论】:

        【解决方案3】:

        与 HashMap 一样,它为基本操作(添加、包含和删除)提供恒定时间性能

        Java 文档中始终解释性能特征。

        https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html

        【讨论】:

          【解决方案4】:

          通过查看https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html,这就是我现在所理解的:

          LinkedHahsMap 顾名思义,结合了 HashMap 和 LinkedList 以提供对 get/put/contains 的 O(1) 操作。我之前对 TreeMap 感到困惑。换句话说,它以可预测的顺序(插入顺序)维护了 HashMap 提供的内容

          This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.

          这与 LRU 非常相似:https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)

          LHM 的实现自然需要为每个元素存储额外的 LinkedList。

          【讨论】:

            猜你喜欢
            • 2019-06-26
            • 1970-01-01
            • 2018-07-26
            • 1970-01-01
            • 2016-12-19
            • 2023-04-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-12
            相关资源
            最近更新 更多