From 3380c12af9af8e9828e44f08880f8130b2a602d8 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Sun, 6 Oct 2019 18:55:35 +0200 Subject: [PATCH] Prefer the faster and more idiomatic Array#map in json_clone (#4313) * Prefer the faster Array#map to a manual implementation * On the benchmark from https://github.com/mperham/sidekiq/pull/4303 on MRI 2.6.4, before 396657.9 i/s, after 461013.3 i/s. * Use `duped` as the return value in the only branch it's needed --- lib/sidekiq/processor.rb | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/lib/sidekiq/processor.rb b/lib/sidekiq/processor.rb index d07f73a4..158117bb 100644 --- a/lib/sidekiq/processor.rb +++ b/lib/sidekiq/processor.rb @@ -279,24 +279,20 @@ module Sidekiq # been mutated by the worker. def json_clone(obj) if Integer === obj || Float === obj || TrueClass === obj || FalseClass === obj || NilClass === obj - return obj + obj elsif String === obj - return obj.dup + obj.dup elsif Array === obj - duped = Array.new(obj.size) - obj.each_with_index do |value, index| - duped[index] = json_clone(value) - end + obj.map { |e| json_clone(e) } elsif Hash === obj duped = obj.dup duped.each_pair do |key, value| duped[key] = json_clone(value) end + duped else - duped = obj.dup + obj.dup end - - duped end end end