You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 a Set<T> (typically a LinkedHashSet, 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 a List<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:

  1. 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!
  2. When the source is a List or 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), vs list.contains(element) which is O(n)).
    • You don't need index-based access to elements.
  • Choose distinct() if:
    • You need a List for 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).

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:44:11