【发布时间】:2013-05-02 19:56:51
【问题描述】:
我想知道在哪些情况下哪些数据结构最适合使用“包含”或“存在”检查。
我问是因为我来自 Python 背景,并且习惯于使用if x in something: 表达式来处理所有事情。例如,哪些表达式的计算速度最快:
val m = Map(1 -> 1, 2 -> 2, 3 -> 3, 4 -> 4)
//> m : scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3, 4
//| -> 4)
val l = List(1,2,3,4) //> l : List[Int] = List(1, 2, 3, 4)
val v = Vector(1,2,3,4) //> v : scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4)
m.exists(_._1 == 3) //> res0: Boolean = true
m.contains(3) //> res1: Boolean = true
l.exists(_ == 3) //> res2: Boolean = true
l.contains(3) //> res3: Boolean = true
v.exists(_ == 3) //> res4: Boolean = true
v.contains(3) //> res5: Boolean = true
直观地说,我认为向量应该是最快的随机检查,如果知道检查的值在列表的开头并且有很多数据,那么列表将是最快的。但是,非常欢迎确认或更正。此外,请随时扩展到其他数据结构。
注意:如果您觉得这个问题过于模糊,请告诉我,因为我不确定我的措辞是否正确。
【问题讨论】:
-
在 Python 中,与所有其他语言一样,当您主要需要成员资格检查时,选择的抽象数据类型是 集合,而不是序列或映射。
-
检查特定元素不是随机检查,它是对向量/列表/数组的短循环全扫描:取第一个元素,比较,如果不是等于,取第二,比较,...。另一方面,集合和地图上的
contains意味着是恒定时间的(与存在不同,它必须首先应用一些谓词,因此我认为也是线性的)
标签: performance scala data-structures scala-collections