Last active
December 8, 2015 08:32
-
-
Save c-lliope/90017f7d74f19e80b789 to your computer and use it in GitHub Desktop.
benchmarking selectively fetching keys from a ruby hash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results
In percentage terms (going off of the
real
column):