Skip to content

Instantly share code, notes, and snippets.

@kevinvanderlugt
Last active December 17, 2015 02:29
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 kevinvanderlugt/5536619 to your computer and use it in GitHub Desktop.
Save kevinvanderlugt/5536619 to your computer and use it in GitHub Desktop.
Ruby sort and sort_by benchmarks for reverse sorting an array of random integers. Just for curiosity, run on your machine to verify
require 'benchmark'
array = []
1000.times {
array << rand(100)
}
sort_count = 10_000
default_sort_time = Benchmark.realtime do
sort_count.times { array.sort.reverse }
end
reverse_time = Benchmark.realtime do
sort_count.times { array.sort { |a, b| a <=> b}.reverse }
end
sort_time = Benchmark.realtime do
sort_count.times { array.sort { |a, b| b <=> a } }
end
sort_by_time = Benchmark.realtime do
sort_count.times { array.sort_by{ |a| a }.reverse }
end
puts "# Sort Results:"
puts "# default sort reverse time: #{default_sort_time} s"
puts "# sort reverse time: #{reverse_time} s"
puts "# sort time: #{sort_time} s"
puts "# sort_by time: #{sort_by_time} s"
# Sort Results v1.9.3p374:
# default sort reverse time: 0.781823 s
# sort reverse time: 9.227052 s
# sort time: 9.530211 s
# sort_by time: 5.209845 s
# Sort Results v1.8.7 (2012-02-08 patchlevel 358) [universal-darwin12.0]:
# default sort reverse time: 0.790833950042725 s
# sort reverse time: 34.1829149723053 s
# sort time: 34.431547164917 s
# sort_by time: 6.2161967754364 s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment