top of page

Performance Comparison: Finding the Two Smallest Numbers in Ruby

  • RFilo CTO
  • 13 de ago.
  • 1 min de leitura

Performance Comparison: Finding the Two Smallest Numbers in Ruby
Its time to choice

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


rails-rtoledo_edited.png

Hi, I'm Rodrigo Toledo

A full-stack developer skilled in both front-end and back-end development, building and maintaining web applications

  • Facebook
  • Youtube
  • LinkedIn
  • Instagram

I don't know everything, help me

I'm always seeking to improve what I build and to refine my skills. Whenever I master something, I share it. And when I don't understand, I dive deep until I do—learning, growing, and helping others along the way.

Subscribe

Thanks for submitting!

bottom of page