If you are sure that you won't have duplicates, then you should use a Seq
like Vector
. The reason is that Set
has extra overhead: it has to hash every element and possibly check equality against some other elements. Depending on how many elements you have and how complex they are, this may be something you want to avoid.
A demonstration:
class A(val name: Int) {
override def hashCode() = {
println(f"hashing $name")
name.hashCode
}
override def equals(other: Any) = other match {
case a: A =>
println(f"$name =?= ${a.name}")
name == a.name
case _ => false
}
}
val elements = (0 to 10).map(new A(_))
println("TO VECTOR")
val seq = Vector.empty ++ elements
println("TO SET")
val set = Set.empty ++ elements
prints:
TO VECTOR // Notice no extra work was done
TO SET // Lots of extra stuff done:
1 =?= 0
2 =?= 0
2 =?= 1
3 =?= 0
3 =?= 1
3 =?= 2
4 =?= 0
4 =?= 1
4 =?= 2
4 =?= 3
hashing 0
hashing 1
hashing 2
hashing 3
hashing 4
hashing 5
hashing 6
hashing 7
hashing 8
hashing 9
hashing 10