Skip to content

Instantly share code, notes, and snippets.

@koic
Last active December 29, 2016 06:00
Show Gist options
  • Save koic/4c159a4aa7d5ea65261a4fdb1e808977 to your computer and use it in GitHub Desktop.
Save koic/4c159a4aa7d5ea65261a4fdb1e808977 to your computer and use it in GitHub Desktop.
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