From 1a73062758bedc2bfb1cc554a7a8ebe1c56394f1 Mon Sep 17 00:00:00 2001 From: Holger Just Date: Fri, 16 Jun 2017 23:01:23 +0200 Subject: [PATCH] Avoid Array instances when JSON'ifying Arrays / Hashes Similar to the previous commit, we avoid the unnecessary allocation of a temporary array when looping over the `@raw` value. In addition to that, we ensure thread-safety by always operating on a copy of the raw data so that other threads can not change anything under our feet anymore. --- lib/rackstash/fields/array.rb | 2 +- lib/rackstash/fields/hash.rb | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/rackstash/fields/array.rb b/lib/rackstash/fields/array.rb index 6470626..af6685b 100644 --- a/lib/rackstash/fields/array.rb +++ b/lib/rackstash/fields/array.rb @@ -89,7 +89,7 @@ module Rackstash # @return [::Array] deep-transforms the array into a plain Ruby Array def as_json(*) - @raw.map { |value| + @raw.to_a.map! { |value| value.is_a?(AbstractCollection) ? value.as_json : value } end diff --git a/lib/rackstash/fields/hash.rb b/lib/rackstash/fields/hash.rb index 839092a..5665cfa 100644 --- a/lib/rackstash/fields/hash.rb +++ b/lib/rackstash/fields/hash.rb @@ -54,9 +54,9 @@ module Rackstash # @return [::Hash] deep-transforms the hash into a plain Ruby Hash def as_json(*) - @raw.each_with_object({}) do |(key, value), memo| - value = value.as_json if value.is_a?(AbstractCollection) - memo[key] = value + hash = @raw.to_h + hash.each_pair do |key, value| + hash[key] = value.as_json if value.is_a?(AbstractCollection) end end alias to_hash as_json