Last active
April 18, 2021 10:35
-
-
Save timoschilling/368cf3c61bcb3d49ce8cd6b44384fd12 to your computer and use it in GitHub Desktop.
Benchmark Hash#except
This file contains 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/ips' | |
require 'active_support/hash_with_indifferent_access' | |
require 'active_support/core_ext/hash' | |
class Hash | |
def except_new(*keys) | |
slice(*(self.keys - keys)) | |
end | |
end | |
class ActiveSupport::HashWithIndifferentAccess | |
def except_new(*keys) | |
slice(*(self.keys - keys.map { |key| convert_key(key) } )) | |
end | |
alias values_at_old values_at | |
def values_at(*keys) | |
super(*keys.map { |key| convert_key(key) }) | |
end | |
end | |
HASH = { a: 1, b: 2, c: 3, d:4 } | |
HASH_WITH_INDIFFERENT_ACCESS = ActiveSupport::HashWithIndifferentAccess.new(HASH) | |
def new_hash | |
HASH.except_new(:b, :d) | |
end | |
def old_hash | |
HASH.except(:b, :d) | |
end | |
def new_with_indifferent_access | |
HASH_WITH_INDIFFERENT_ACCESS.except_new(:b, :d) | |
end | |
def old_with_indifferent_access | |
HASH_WITH_INDIFFERENT_ACCESS.except(:b, :d) | |
end | |
Benchmark.ips do |x| | |
x.report("Hash new") { new_hash } | |
x.report("Hash old") { old_hash } | |
x.compare! | |
end | |
Benchmark.ips do |x| | |
x.report("HashWithIndifferentAccess new") { new_with_indifferent_access } | |
x.report("HashWithIndifferentAccess old") { old_with_indifferent_access } | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment