Skip to content

Instantly share code, notes, and snippets.

@amarshall
Created March 2, 2012 18:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amarshall/1960384 to your computer and use it in GitHub Desktop.
Save amarshall/1960384 to your computer and use it in GitHub Desktop.
# Benchmarking for http://stackoverflow.com/questions/9538090
require 'benchmark'
require 'active_support/core_ext'
events = [{id:2, start:"3:30",break:30,num_attendees:14},{id:3, start:"3:40",break: 40,num_attendees:4},{id:4, start:"4:40",break:10,num_attendees:40}]
time = Benchmark.bm(10) do |bm|
bm.report("amarshall 1") do
10000.times do
events.map do |hash|
hash.select do |key, value|
[:id, :start].include? key
end
end
end
end
bm.report("amarshall 2") do
10000.times do
events.map do |hash|
{ id: hash[:id], start: hash[:start] }
end
end
end
bm.report("amarshall 3") do
10000.times do
return_keys = [:id, :start]
events.map do |hash|
{}.tap do |new_hash|
return_keys.each do |key|
new_hash[key] = hash[key]
end
end
end
end
end
bm.report("tadman 1") do
10000.times do
return_keys = [ :id, :start ]
# Compute a quick hash to extract the right values: { key => true }
key_index = Hash[return_keys.collect { |key| [ key, true ] }]
return_array = events.collect do |event|
event.select do |key, value|
key_index[key]
end
end
end
end
bm.report("tadman 2") do
10000.times do
return_keys = [ :id, :start ]
return_array = events.collect do |event|
Hash[
return_keys.collect do |key|
[ key, event[key] ]
end
]
end
end
end
bm.report("mu") do
10000.times do
return_array = events.map { |h| h.slice(:id, :start) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment