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:
parent
9b7549b4d0
commit
da3113e880
@ -114,8 +114,9 @@ module Rackstash
|
|||||||
when Rackstash::Fields::Hash, Rackstash::Fields::Array
|
when Rackstash::Fields::Hash, Rackstash::Fields::Array
|
||||||
return wrap ? value : value.raw
|
return wrap ? value : value.raw
|
||||||
when ::Hash
|
when ::Hash
|
||||||
hash = value.each_with_object(Concurrent::Hash.new) do |(k, v), memo|
|
hash = Concurrent::Hash.new
|
||||||
memo[utf8_encode(k)] = normalize(v, scope: scope)
|
value.each_pair do |k, v|
|
||||||
|
hash[utf8_encode(k)] = normalize(v, scope: scope)
|
||||||
end
|
end
|
||||||
if wrap
|
if wrap
|
||||||
hash = Rackstash::Fields::Hash.new.tap do |hash_field|
|
hash = Rackstash::Fields::Hash.new.tap do |hash_field|
|
||||||
@ -124,8 +125,9 @@ module Rackstash
|
|||||||
end
|
end
|
||||||
return hash
|
return hash
|
||||||
when ::Array, ::Set, ::Enumerator
|
when ::Array, ::Set, ::Enumerator
|
||||||
array = value.each_with_object(Concurrent::Array.new) do |e, memo|
|
array = Concurrent::Array.new
|
||||||
memo << normalize(e, scope: scope)
|
value.each do |e|
|
||||||
|
array << normalize(e, scope: scope)
|
||||||
end
|
end
|
||||||
if wrap
|
if wrap
|
||||||
array = Rackstash::Fields::Array.new.tap do |array_field|
|
array = Rackstash::Fields::Array.new.tap do |array_field|
|
||||||
|
|||||||
@ -224,6 +224,11 @@ describe Rackstash::Fields::AbstractCollection do
|
|||||||
expect(normalize(hash, wrap: false).keys).to all be_frozen
|
expect(normalize(hash, wrap: false).keys).to all be_frozen
|
||||||
end
|
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
|
it 'normalizes all values' do
|
||||||
hash = { 'key' => :beepboop }
|
hash = { 'key' => :beepboop }
|
||||||
|
|
||||||
@ -288,6 +293,11 @@ describe Rackstash::Fields::AbstractCollection do
|
|||||||
expect(normalize(array, wrap: false)).to all be_frozen
|
expect(normalize(array, wrap: false)).to all be_frozen
|
||||||
end
|
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
|
it 'normalizes all values' do
|
||||||
array = ['boop', :beep]
|
array = ['boop', :beep]
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user