Skip to content

Instantly share code, notes, and snippets.

@visfleet
Created September 22, 2009 05:55
Show Gist options
  • Save visfleet/190849 to your computer and use it in GitHub Desktop.
Save visfleet/190849 to your computer and use it in GitHub Desktop.

Revisions

  1. visfleet created this gist Sep 22, 2009.
    44 changes: 44 additions & 0 deletions performance_of_yaml_vs_marshal.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    require 'benchmark'
    require 'yaml'

    def encode(msg, format)
    case format
    when :yaml
    str = msg.to_yaml
    when :binary
    str = Marshal.dump(msg)
    end
    str.gsub!("\n", '--\\n')
    str
    end

    def decode(str, format)
    case format
    when :yaml
    YAML.load(str)
    when :binary
    Marshal.load(str)
    end
    str.gsub!('--\\n', "\n")
    end

    SAMPLES = 1000
    obj = {:test => "me"}

    Benchmark.bm do |r|
    r.report("Marshal") do
    SAMPLES.times do
    decode(encode(obj, :binary), :binary)
    end
    end
    r.report("YAML") do
    SAMPLES.times do
    decode(encode(obj, :yaml), :yaml)
    end
    end
    end

    # Results
    # user system total real
    # Marshal 0.020000 0.000000 0.020000 (0.025426)
    # YAML 0.210000 0.010000 0.220000 (0.218788)