1
0
mirror of https://github.com/meineerde/rackstash.git synced 2025-10-17 14:01:01 +00:00

Avoid Array instances when normalizing Arrays / Hashes

`each_with_object` allocates an array for each kv pair. Switching to
the slightly more verbose but less allocatey `each_pair` eliminates
array allocations.

This follows the similar change in Rails:
960de47f0e
This commit is contained in:
Holger Just 2017-05-23 12:55:27 +02:00
parent 9b7549b4d0
commit da3113e880
2 changed files with 16 additions and 4 deletions

View File

@ -114,8 +114,9 @@ module Rackstash
when Rackstash::Fields::Hash, Rackstash::Fields::Array
return wrap ? value : value.raw
when ::Hash
hash = value.each_with_object(Concurrent::Hash.new) do |(k, v), memo|
memo[utf8_encode(k)] = normalize(v, scope: scope)
hash = Concurrent::Hash.new
value.each_pair do |k, v|
hash[utf8_encode(k)] = normalize(v, scope: scope)
end
if wrap
hash = Rackstash::Fields::Hash.new.tap do |hash_field|
@ -124,8 +125,9 @@ module Rackstash
end
return hash
when ::Array, ::Set, ::Enumerator
array = value.each_with_object(Concurrent::Array.new) do |e, memo|
memo << normalize(e, scope: scope)
array = Concurrent::Array.new
value.each do |e|
array << normalize(e, scope: scope)
end
if wrap
array = Rackstash::Fields::Array.new.tap do |array_field|

View File

@ -224,6 +224,11 @@ describe Rackstash::Fields::AbstractCollection do
expect(normalize(hash, wrap: false).keys).to all be_frozen
end
it 'returns a Concurrent::Hash with wrap: false' do
hash = { 'one' => 1 }
expect(normalize(hash, wrap: false)).to be_an_instance_of(Concurrent::Hash)
end
it 'normalizes all values' do
hash = { 'key' => :beepboop }
@ -288,6 +293,11 @@ describe Rackstash::Fields::AbstractCollection do
expect(normalize(array, wrap: false)).to all be_frozen
end
it 'returns a Concurrent::Array with wrap: false' do
array = [1, :two, 'three']
expect(normalize(array, wrap: false)).to be_an_instance_of(Concurrent::Array)
end
it 'normalizes all values' do
array = ['boop', :beep]