Skip to content

Instantly share code, notes, and snippets.

@davidcelis
Created August 13, 2012 17:58
Show Gist options
  • Save davidcelis/3342764 to your computer and use it in GitHub Desktop.
Save davidcelis/3342764 to your computer and use it in GitHub Desktop.
Benchmark between Array#sort and Array#sort_by.
require 'benchmark'
@ids = (1..1000).to_a.shuffle
@records = []
1000.times do |x|
@records << { :id => (x + 1) }
end
Benchmark.bm do |x|
x.report { @records.sort_by { |r| @ids.index(r[:id]) } }
x.report { @records.sort { |x, y| @ids.index(x[:id]) <=> @ids.index(y[:id]) } }
end
user system total real
0.030000 0.000000 0.030000 ( 0.024707)
0.440000 0.000000 0.440000 ( 0.438650)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment