Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I was wondering the same thing, so I benchmarked a few different techniques against each other. I was primarily concerned with Arrays and Hashes - I didn't test any complex objects. Perhaps unsurprisingly, a custom deep-clone implementation proved to be the fastest. If you are looking for quick and easy implementation, Marshal appears to be the way to go. </p> <p>I also benchmarked an XML solution with Rails 3.0.7, not shown below. It was much, much slower, ~10 seconds for only 1000 iterations (the solutions below all ran 10,000 times for the benchmark).</p> <p>Two notes regarding my JSON solution. First, I used the C variant, version 1.4.3. Second, it doesn't actually work 100%, as symbols will be converted to Strings. </p> <p>This was all run with ruby 1.9.2p180.</p> <pre><code>#!/usr/bin/env ruby require 'benchmark' require 'yaml' require 'json/ext' require 'msgpack' def dc1(value) Marshal.load(Marshal.dump(value)) end def dc2(value) YAML.load(YAML.dump(value)) end def dc3(value) JSON.load(JSON.dump(value)) end def dc4(value) if value.is_a?(Hash) result = value.clone value.each{|k, v| result[k] = dc4(v)} result elsif value.is_a?(Array) result = value.clone result.clear value.each{|v| result &lt;&lt; dc4(v)} result else value end end def dc5(value) MessagePack.unpack(value.to_msgpack) end value = {'a' =&gt; {:x =&gt; [1, [nil, 'b'], {'a' =&gt; 1}]}, 'b' =&gt; ['z']} Benchmark.bm do |x| iterations = 10000 x.report {iterations.times {dc1(value)}} x.report {iterations.times {dc2(value)}} x.report {iterations.times {dc3(value)}} x.report {iterations.times {dc4(value)}} x.report {iterations.times {dc5(value)}} end </code></pre> <p>results in:</p> <pre><code>user system total real 0.230000 0.000000 0.230000 ( 0.239257) (Marshal) 3.240000 0.030000 3.270000 ( 3.262255) (YAML) 0.590000 0.010000 0.600000 ( 0.601693) (JSON) 0.060000 0.000000 0.060000 ( 0.067661) (Custom) 0.090000 0.010000 0.100000 ( 0.097705) (MessagePack) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload