在scala中,为什么Range.hashCode()是如此之慢并且不能更快?

问题描述 投票:0回答:1

考虑以下代码:

  def timed[T](fn: => T): (T, Long) = {
    val startTime = System.currentTimeMillis()
    val result = fn
    val endTime = System.currentTimeMillis()
    (result, endTime - startTime)
  }

val t1 = timed((0 until Int.MaxValue).hashCode())
val t2 = timed((0, Int.MaxValue).hashCode())

print(t1 + " : " + t2)

从理论上讲,Range的hashCode()的速度可以与Tuple相媲美,相反,速度的差异是惊人的:

(201341306,5274) : (-281813831,0)

事实证明,Range继承了IndexSeq的hashCode()实现,这需要完整的迭代。我的问题是,是否可以加快速度?是什么阻止它实施?

scala range hashcode
1个回答
2
投票

在scala标准库中,如果内容相等,则所有顺序集合都被视为equal

Vector(1,2,3) == List(1,2,3) //true

而且由于equals / hashcode合约哈希码必须以相同的方式为每种类型的集合计算。

© www.soinside.com 2019 - 2024. All rights reserved.