require 'ostruct'
require 'benchmark'
ITERATIONS = 10_000_000
FOO = "Bar"
BAZ = "Bat"
NewStruct = Struct.new(:foo, :bar)
class Thingie
attr_accessor :foo, :bar
end
class ThingieStruct < Struct.new(:foo, :bar)
attr_accessor :foo, :bar
end
Benchmark.bm(8) do |b|
b.report("struct:") do
ITERATIONS.times do
p = NewStruct.new
p.foo = FOO
p.bar = BAZ
end
end
b.report("class:") do
ITERATIONS.times do
p = Thingie.new
p.foo = FOO
p.bar = BAZ
end
end
b.report("struct-class:") do
ITERATIONS.times do
p = ThingieStruct.new
p.foo = FOO
p.bar = BAZ
end
end
end
user system total real
struct: 2.540000 0.000000 2.540000 ( 2.546056)
class: 1.740000 0.010000 1.750000 ( 1.748066)
struct-class: 8.490000 0.130000 8.620000 ( 8.629484)