Skip to content

Instantly share code, notes, and snippets.

@timoschilling
Last active April 18, 2021 10:35
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 timoschilling/368cf3c61bcb3d49ce8cd6b44384fd12 to your computer and use it in GitHub Desktop.
Save timoschilling/368cf3c61bcb3d49ce8cd6b44384fd12 to your computer and use it in GitHub Desktop.
Benchmark Hash#except
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