Skip to content

Instantly share code, notes, and snippets.

@workmad3
Created June 11, 2015 11:57
Show Gist options
  • Save workmad3/25e4a0a617a7e3639d14 to your computer and use it in GitHub Desktop.
Save workmad3/25e4a0a617a7e3639d14 to your computer and use it in GitHub Desktop.
require 'ostruct'
require 'benchmark'
COUNT = 10_000_000
NAME = "Test Name"
EMAIL = "[email protected]"
class SimpleOstruct
def initialize(attrs = {})
@attrs = attrs
end
def method_missing(name, *args)
if name.to_s =~ /=$/
@attrs[name.to_s[0..-2]] = args.first
else
@attrs[name] = args.first
end
end
end
class Person
attr_accessor :name, :email
end
Benchmark.bm(13) do |x|
x.report("hash:") do
COUNT.times do
p = { name: NAME, email: EMAIL }
end
end
x.report("openstruct:") do
COUNT.times do
p = OpenStruct.new
p.name = NAME
p.email = EMAIL
end
end
x.report("simple_openstruct:") do
COUNT.times do
p = SimpleOstruct.new
p.name = NAME
p.email = EMAIL
end
end
x.report("struct:") do
PersonStruct = Struct.new(:name, :email)
COUNT.times do
p = PersonStruct.new
p.name = NAME
p.email = EMAIL
end
end
x.report("class:") do
COUNT.times do
p = Person.new
p.name = NAME
p.email = EMAIL
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment