Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HashWithIndifferentAccess#initialize performance improvement #34642

Merged
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

HashWithIndifferentAccess#initialize performance improvement

Rails 4 -> Rails 5 introduced a #to_hash call in
HashWithIndifferentAccess#initialize to guarantee access to
the #default and #default_proc methods.  This can be a very
expensive operation for very large HashWithIndifferentAccess
objects.  This commit bypasses this #to_hash call if it is
already a Hash.
  • Loading branch information...
azimux committed Dec 6, 2018
commit 75a2ca6e9dca2c36d80478bcc78ac7bd25bf38f7
@@ -69,7 +69,7 @@ def initialize(constructor = {})
super()
update(constructor)

hash = constructor.to_hash
hash = constructor.is_a?(Hash) ? constructor : constructor.to_hash
self.default = hash.default if hash.default
self.default_proc = hash.default_proc if hash.default_proc
else
@@ -828,4 +828,32 @@ def test_should_copy_the_default_proc_when_converting_to_hash_with_indifferent_a
assert_equal 3, hash_wia[:foo]
assert_equal 3, hash_wia[:bar]
end

def test_should_copy_the_default_when_converting_non_hash_to_hash_with_indifferent_access
non_hash = Object.new

def non_hash.to_hash
h = { foo: :bar }
h.default = :baz
h
end

hash_wia = HashWithIndifferentAccess.new(non_hash)
assert_equal :bar, hash_wia[:foo]
assert_equal :baz, hash_wia[:missing]
end

def test_should_copy_the_default_proc_when_converting_non_hash_to_hash_with_indifferent_access
non_hash = Object.new

def non_hash.to_hash
h = { foo: :bar }
h.default_proc = ->(hash, key) { hash[key] = :baz }
h
end

hash_wia = HashWithIndifferentAccess.new(non_hash)
assert_equal :bar, hash_wia[:foo]
assert_equal :baz, hash_wia[:missing]
end
end
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.