Matthew Layton
Matthew Layton

Reputation: 42270

Kotlin - toSet() versus distinct()

In Kotlin, I could obtain the distinct elements of an Iterable<T> using the following two methods...

Calling .toSet()

val items = listOf(1, 2, 2, 3)
val distinctItems: Set<Int> = items.toSet()

Calling .distinct()

val items = listOf(1, 2, 2, 3)
val distinctItems: List<Int> = items.distinct()

Aside from the fact that the return type is different (Set<Int> versus List<Int>) is there any advantage (i.e. performance) of calling one over the other?

Note: It seems that Kotlin favours the use of List<T> over Set<T> for most operations, and I guess that makes sense where lists of items are probably more common than sets of items. I tend to use Set<T> more often than not, especially where set semantics make more sense than list semantics.

Upvotes: 6

Views: 1798

Answers (1)

leonardkraemer
leonardkraemer

Reputation: 6793

Iterable.distinct() uses a Set internally. So basically you can expect O(#distinctElements) of performance impact.

For example https://github.com/JetBrains/kotlin/blob/acd29481bd9ca68739c73140f0bdbd9b9cdb22b4/libraries/stdlib/common/src/generated/_Collections.kt#L1609

public fun <T> Iterable<T>.distinct(): List<T> {
    return this.toMutableSet().toList()
}

Upvotes: 4

Related Questions