Skip to content

Instantly share code, notes, and snippets.

@c-lliope
Last active December 8, 2015 08:32
Show Gist options
  • Save c-lliope/90017f7d74f19e80b789 to your computer and use it in GitHub Desktop.
Save c-lliope/90017f7d74f19e80b789 to your computer and use it in GitHub Desktop.
benchmarking selectively fetching keys from a ruby hash
require 'benchmark'
ATTRIBUTE_TYPES = {}.tap do |hash|
struct = Struct.new(:searchable?)
50.times do |i|
searchable_val = [true, false].sample
hash[i] = struct.new(searchable_val)
end
end
n = 1_000_000
Benchmark.bm do |x|
x.report("select{}.keys ") do
n.times do
ATTRIBUTE_TYPES.select do |_, type|
type.searchable?
end.keys
end
end
x.report("keys.select{} ") do
n.times do
ATTRIBUTE_TYPES.keys.select do |key|
ATTRIBUTE_TYPES[key].searchable?
end
end
end
x.report("keys.select!{} ") do
n.times do
ATTRIBUTE_TYPES.keys.select! do |key|
ATTRIBUTE_TYPES[key].searchable?
end
end
end
x.report("[].tap { x << key } ") do
n.times do
[].tap do |keys|
ATTRIBUTE_TYPES.each do |key, type|
keys << key if type.searchable?
end
end
end
end
x.report("each_with_object([])") do
n.times do
ATTRIBUTE_TYPES.each_with_object([]) do |(key, type), keys|
keys << key if type.searchable?
end
end
end
end
@c-lliope
Copy link
Author

c-lliope commented Dec 8, 2015

Results

                     user     system      total        real
select{}.keys        15.060000   0.160000  15.220000 ( 15.360678)
keys.select{}        11.590000   0.140000  11.730000 ( 11.951267)
keys.select!{}       10.600000   0.070000  10.670000 ( 10.841434)
[].tap { x << key }  10.550000   0.050000  10.600000 ( 10.721592)
each_with_object([]) 14.880000   0.030000  14.910000 ( 15.078155)

In percentage terms (going off of the real column):

select{}.keys        |  0    %
keys.select{}        | 22.195%
keys.select!{}       | 29.420%
[].tap { x << key }  | 30.201%
each_with_object([]) |  1.839%

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment