Juste pour voir ce qui était plus rapide:
require 'fruity'
AGES = { "Bruce" => 32, "Clark" => 28 }
MAPPINGS = {"Bruce" => "Bruce Wayne", "Clark" => "Clark Kent"}
def jörg_w_mittag_test(ages, mappings)
Hash[ages.map {|k, v| [mappings[k], v] }]
end
require 'facets/hash/rekey'
def tyler_rick_test(ages, mappings)
ages.rekey(mappings)
end
def barbolo_test(ages, mappings)
ages.keys.each { |k| ages[ mappings[k] ] = ages.delete(k) if mappings[k] }
ages
end
class Hash
def tfr_rekey(h)
dup.tfr_rekey! h
end
def tfr_rekey!(h)
h.each { |k, newk| store(newk, delete(k)) if has_key? k }
self
end
end
def tfr_test(ages, mappings)
ages.tfr_rekey mappings
end
class Hash
def rename_keys(mapping)
result = {}
self.map do |k,v|
mapped_key = mapping[k] ? mapping[k] : k
result[mapped_key] = v.kind_of?(Hash) ? v.rename_keys(mapping) : v
result[mapped_key] = v.collect{ |obj| obj.rename_keys(mapping) if obj.kind_of?(Hash)} if v.kind_of?(Array)
end
result
end
end
def greg_test(ages, mappings)
ages.rename_keys(mappings)
end
compare do
jörg_w_mittag { jörg_w_mittag_test(AGES.dup, MAPPINGS.dup) }
tyler_rick { tyler_rick_test(AGES.dup, MAPPINGS.dup) }
barbolo { barbolo_test(AGES.dup, MAPPINGS.dup) }
greg { greg_test(AGES.dup, MAPPINGS.dup) }
end
Quelles sorties:
Exécuter chaque test 1024 fois. Le test prendra environ 1 seconde.
barbolo est plus rapide que jörg_w_mittag de 19.999999999999996% ± 10.0%
jörg_w_mittag est plus rapide que greg de 10.000000000000009% ± 10.0%
greg est plus rapide que tyler_rick de 30.000000000000004% ± 10.0%