Created
January 24, 2014 05:49
-
-
Save palexander/8592601 to your computer and use it in GitHub Desktop.
Benchmark to compare hash, OpenStruct, struct, and classes in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'ostruct' | |
require 'benchmark' | |
COUNT = 10_000_000 | |
NAME = "Test Name" | |
EMAIL = "[email protected]" | |
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