Skip to content

Instantly share code, notes, and snippets.

@palexander
Created January 24, 2014 05:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save palexander/8592601 to your computer and use it in GitHub Desktop.
Save palexander/8592601 to your computer and use it in GitHub Desktop.
Benchmark to compare hash, OpenStruct, struct, and classes in Ruby
require 'ostruct'
require 'benchmark'
COUNT = 10_000_000
NAME = "Test Name"
EMAIL = "test@example.org"
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("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
user system total real
hash: 4.610000 0.250000 4.860000 ( 4.857328)
openstruct: 134.900000 2.830000 137.730000 (137.811739)
struct: 3.940000 0.000000 3.940000 ( 3.943897)
class: 2.480000 0.000000 2.480000 ( 2.486405)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment