Project

General

Profile

Bug #16243 » case_vs_if.rb

Eregon (Benoit Daloze), 10/06/2019 04:11 PM

 
# frozen_string_literal: true
require "benchmark/ips"

def deep_dup_case(obj)
case obj
when Integer, Float, TrueClass, FalseClass, NilClass
obj
when String
obj.dup
when Array
obj.map { |e| deep_dup_case(e) }
when Hash
duped = obj.dup
duped.each_pair do |key, value|
duped[key] = deep_dup_case(value)
end
else
obj.dup
end
end

def deep_dup_if(obj)
if Integer === obj || Float === obj || TrueClass === obj || FalseClass === obj || NilClass === obj
obj
elsif String === obj
obj.dup
elsif Array === obj
obj.map { |e| deep_dup_if(e) }
elsif Hash === obj
duped = obj.dup
duped.each_pair do |key, value|
duped[key] = deep_dup_if(value)
end
duped
else
obj.dup
end
end


obj = { "class" => "FooWorker", "args" => [1, 2, 3, "foobar"], "jid" => "123987123" }

Benchmark.ips do |x|
x.report("deep_dup_case") do
deep_dup_case(obj)
end

x.report("deep_dup_if") do
deep_dup_if(obj)
end

x.compare!
end
(1-1/2)