Skip to content

Instantly share code, notes, and snippets.

@kenjiskywalker
Created April 27, 2015 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenjiskywalker/2fbfc9d00e0b4f7377eb to your computer and use it in GitHub Desktop.
Save kenjiskywalker/2fbfc9d00e0b4f7377eb to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'benchmark'
# Struct
s = Struct.new(:foo, :bar, :baz)
s = s.new(nil, nil, nil)
# Hash
h = {foo: nil, bar: nil, baz: nil}
n = 5000000
Benchmark.bm do |m|
# test assignment and access for Hash and Struct
m.report { n.times do; h[:foo] = n, h[:bar] = n, h[:baz]; end }
m.report { n.times do; s.foo = n, s.bar = n, s.baz = n; end }
end
# $ ruby struct_vs_hash.rb
# user system total real
# 1.510000 0.010000 1.520000 ( 1.548214)
# 2.120000 0.030000 2.150000 ( 2.227257)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment