public
Created

  • Download Gist
so-9538090-bm.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.