Performance Comparison: Finding the Two Smallest Numbers in Ruby
- RFilo CTO
- 13 de ago.
- 1 min de leitura

When working with large datasets in Ruby, choosing the right method to find the two smallest numbers can impact performance. Let’s compare two common approaches:
Using sort.take(2)
Sorts the entire array first
Time complexity: O(n log n)
Simple but inefficient for large arrays
Using min(2)
Finds the two smallest elements directly
Time complexity: O(n)
More efficient, especially for big datasets
For small arrays, both work fine. But with thousands of elements, min(2) is clearly faster as it avoids full sorting.
Comentários