Skip to content

Instantly share code, notes, and snippets.

@protist
Created September 12, 2014 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save protist/380ec7f0a3a53c7835f0 to your computer and use it in GitHub Desktop.
Save protist/380ec7f0a3a53c7835f0 to your computer and use it in GitHub Desktop.
Benchmark to compare sort_by and sort for an array that contains orderable values within hashes.
#!/usr/bin/env ruby
require 'benchmark'
max = 100_000
a = []
flip_flop = false
(1..max).each do |i|
if flip_flop
a.unshift({c:[i, i+1]})
flip_flop = false
else
a.push({c:[i, i+1]})
flip_flop = true
end
end
Benchmark.bmbm do |bm|
bm.report('sort_by') do
a.sort_by { |x| x[:c] }
end
bm.report('sort') do
a.sort { |x, y| x[:c] <=> y[:c] }
end
end
@protist
Copy link
Author

protist commented Sep 12, 2014

              user     system      total        real
sort_by   0.500000   0.000000   0.500000 (  0.507925)
sort      0.820000   0.000000   0.820000 (  0.819071)

sort starts getting competitive when array size (max) is reduced to ~100.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment