Created
September 12, 2014 06:14
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sort
starts getting competitive when array size (max
) is reduced to ~100.