Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/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
You can’t perform that action at this time.