Skip to content

Instantly share code, notes, and snippets.

@koic koic/sort_vs_sort_by.md
Last active Dec 29, 2016

Embed
What would you like to do?
Enumerable#sort vs Enumerable#sort_by

Enumerable#sort without block

# http://ruby-doc.org/core-2.3.1/Enumerable.html#method-i-sort
require "benchmark"

a = (1..100000).map { rand(100000) }

Benchmark.bm(10) do |b|
  b.report("Sort")    { a.sort }
  b.report("Sort by") { a.sort_by { |a| a } }
end

produces:

                 user     system      total        real
Sort         0.010000   0.000000   0.010000 (  0.017413)
Sort by      0.090000   0.000000   0.090000 (  0.087715)

Enumerable#sort with block

require 'benchmark'

a = (1..100000).map { rand(100000) }

Benchmark.bm(10) do |b|
  b.report("Sort")    { a.sort { |a, b| a.to_s <=> b.to_s } }
  b.report("Sort by") { a.sort_by(&:to_s) }
end

produces:

                 user     system      total        real
Sort         0.570000   0.000000   0.570000 (  0.571723)
Sort by      0.130000   0.000000   0.130000 (  0.129793)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.