Skip to content

Instantly share code, notes, and snippets.

@franzejr
Created December 16, 2015 12:01
Show Gist options
  • Save franzejr/ed4201e90abebbcfc83e to your computer and use it in GitHub Desktop.
Save franzejr/ed4201e90abebbcfc83e to your computer and use it in GitHub Desktop.
Sort and Sort_by for dates
require 'active_support/all'
require 'benchmark'
dates = []
5.times {
dates << Time.at(rand * Time.now.to_i).utc
}
puts 'DESC SORT WITH COMPARATOR'
puts dates.sort {|x,y| y <=> x }
puts 'DESC SORT_BY'
puts dates.sort_by {|x| Time.now - x}
puts 'SORT_BY'
puts dates.sort_by {|x| x }
100000.times {
dates << Time.at(rand * Time.now.to_i).utc
}
Benchmark.bm do |x|
x.report('sort') { dates.sort {|x,y| y <=> x } }
x.report('sort_by') { dates.sort_by {|x| Time.now - x } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment