Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Last active September 25, 2019 08:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petitviolet/dc5b44fae57277ae915bd770ba4f2435 to your computer and use it in GitHub Desktop.
Save petitviolet/dc5b44fae57277ae915bd770ba4f2435 to your computer and use it in GitHub Desktop.
[Scala]Set#map is slow

Set#map is slow

example code

Implement custom class with overriding hashCode and equals methods.

case class Value(x: Int) { 
    override def hashCode = { 
        println(s"hashCode: $x")
        x
    }
    override def equals(other: Any) = { 
        println(s"equals: $this == $other??")
        other match {
            case v: Value => v.x == this.x
            case _ => false       
        }
    }
}

execution result

First, Seq#map.

scala> val result = (1 to 5).toSeq.map { Value.apply } .map { v => Value(v.x % 2) }
result: scala.collection.immutable.IndexedSeq[Value] = Vector(Value(1), Value(0), Value(1), Value(0), Value(1))

Second, Set#map.

scala> val result = (1 to 5).toSet.map { Value.apply } .map { v => Value(v.x % 2) }
hashCode: 5
hashCode: 1
hashCode: 2
hashCode: 3
hashCode: 4
hashCode: 1
hashCode: 1
equals: Value(1) == Value(1)??
hashCode: 0
hashCode: 1
equals: Value(1) == Value(1)??
hashCode: 0
equals: Value(0) == Value(0)??
result: scala.collection.immutable.Set[Value] = Set(Value(0), Value(1))

the reason why Set#map is slow

Executing Set#map also hashCode and equals are invoked to stay as a Set instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment