scala - Scala 不可变索引序列是如何实现的,它们的操作复杂度如何?

标签 scala time-complexity scala-collections seq

我依稀记得在某处读到 Scala 的不可变索引序列操作是 O(log n),但是对数的底足够大,因此对于所有实际目的,操作几乎就像 O(log n) em>O(1)。是真的吗?

IndexedSeq 是如何实现的?

最佳答案

immutable.IndexedSeq 的默认实现是Vector。这是 relevant documentation 的摘录关于它的实现:

Vectors are represented as trees with a high branching factor (The branching factor of a tree or a graph is the number of children at each node). Every tree node contains up to 32 elements of the vector or contains up to 32 other tree nodes. Vectors with up to 32 elements can be represented in a single node. Vectors with up to 32 * 32 = 1024 elements can be represented with a single indirection. Two hops from the root of the tree to the final element node are sufficient for vectors with up to 2^15 elements, three hops for vectors with 2^20, four hops for vectors with 2^25 elements and five hops for vectors with up to 2^30 elements. So for all vectors of reasonable size, an element selection involves up to 5 primitive array selections. This is what we meant when we wrote that element access is “effectively constant time”.

immutable.HashSetimmutable.HashMap 使用类似的技术实现。

关于scala - Scala 不可变索引序列是如何实现的,它们的操作复杂度如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23040559/

相关文章:

java - 以下方法的时间复杂度

list - 如何在列表中查找重复项?

arrays - 如果 Scala 中需要不可变数组,返回 IndexesSeq 而不是 Array 是否正确?

algorithm - 最短路径算法 : Dynamic Programming vs Dijkstra's algorithm

scala - Joda Time : Convert UTC to local

java - 为什么 Spark 在本地模式下失败并显示 "Failed to get broadcast_0_piece0 of broadcast_0"?

scala - Spark /SQL :spark can't resolve symbol toDF

java - 如何使用 O(n) 时间复杂度算法查找有效子字符串的数量

从可迭代对象创建集合时,Scala 是否必须转换为 Seq?

scala - 如何在 Flink 中使用多个计数器