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

Optimize Hash#transform_{keys,values} #14502

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 24 additions & 4 deletions src/hash.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1690,8 +1690,18 @@ class Hash(K, V)
# hash.transform_keys { |key, value| key.to_s * value } # => {"a" => 1, "bb" => 2, "ccc" => 3}
# ```
def transform_keys(& : K, V -> K2) : Hash(K2, V) forall K2
each_with_object({} of K2 => V) do |(key, value), memo|
memo[yield(key, value)] = value
if size <= 4
# Building up an empty hash is faster than a pre-allocated one as long as
# the size is below 5.
each_with_object({} of K2 => V) do |(key, value), memo|
memo[yield(key, value)] = value
end
else
hash = Hash(K2, V).new(initial_capacity: size)
each do |key, value|
hash[yield(key, value)] = value
end
hash
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we merge the branches? Like:

copy = size > 4 ? Hash(K2, V).new(capacity) : Hash(K2, V).new
each_with_object(copy) { ... }

Maybe 4 could be a constant instead of a magic number? For example Hash::INITIAL_CAPACITY or Hash::MINIMAL_CAPACITY.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It can be even simpler: Hash(K2, V).new(size < 4 ? 0 : size)

end
end

Expand All @@ -1705,8 +1715,18 @@ class Hash(K, V)
# hash.transform_values { |value, key| "#{key}#{value}" } # => {:a => "a1", :b => "b2", :c => "c3"}
# ```
def transform_values(& : V, K -> V2) : Hash(K, V2) forall V2
each_with_object({} of K => V2) do |(key, value), memo|
memo[key] = yield(value, key)
if size <= 4
# Building up an empty hash is faster than a pre-allocated one as long as
# the size is below 5.
each_with_object({} of K => V2) do |(key, value), memo|
memo[key] = yield(value, key)
end
else
hash = Hash(K, V2).new(initial_capacity: size)
each do |key, value|
hash[key] = yield(value, key)
end
hash
end
end

Expand Down