Kotlin中toSet()与distinct()的对比:除返回类型外的性能及使用优势探究
toSet() vs distinct() in Kotlin: Performance & Use Case Comparison Great question! Let's break down how these two methods differ, including performance implications and which one fits your scenario best.
Basic Usage Recap
First, a quick refresher on how each method works with code examples:
toSet(): Converts the iterable to aSet<T>(typically aLinkedHashSet, which preserves the original insertion order):val items = listOf(1, 2, 2, 3) val distinctSet: Set<Int> = items.toSet() // Result: [1, 2, 3] (as a Set)distinct(): Returns aList<T>containing only unique elements, also preserving insertion order:val items = listOf(1, 2, 2, 3) val distinctList: List<Int> = items.distinct() // Result: [1, 2, 3] (as a List)
Performance Breakdown
The performance gap depends heavily on your source collection and what you're doing with the result:
- When the source is already a
Set:toSet()is blazingly fast—it just returns the original set directly, no copying or iteration required.distinct()wastes cycles here: it creates a new mutable set and list, then iterates through every element anyway. Avoid this if you're starting with a set!
- When the source is a
Listor non-set iterable:- Both methods run in O(n) amortized time (since HashSet operations are average O(1)).
toSet()is slightly more efficient: it only creates one collection (LinkedHashSet) to store unique elements.distinct()creates two collections: a mutable set to track seen elements, plus a mutable list to build the final result. The overhead is small for most datasets, but adds up with very large lists.
Semantics & Use Case Fit
Performance isn't everything—semantics and compatibility matter too:
- Choose
toSet()if:- You need set semantics (you want to enforce uniqueness, or prevent duplicates from being added later).
- You'll frequently check if elements exist (
set.contains(element)is O(1), vslist.contains(element)which is O(n)). - You don't need index-based access to elements.
- Choose
distinct()if:- You need a
Listfor compatibility with Kotlin's standard library (which leans heavily on lists for common operations). - You need to perform list-specific tasks like slicing, sorting, or accessing elements by index.
- You want to avoid converting a set back to a list later (which adds extra overhead).
- You need a
Final Takeaway
There's no universal "better" method—it all depends on your needs. If uniqueness and fast lookups are your priorities, go with toSet(). If you need list functionality or seamless API compatibility, distinct() is the right call. And remember: if your source is already a set, toSet() is the obvious performance win.
内容的提问来源于stack exchange,提问作者Matthew Layton

