Forked from palexander/ruby_data_object_comparison.rb
Last active
September 17, 2020 12:24
-
-
Save skatkov/c32ffff81dc22e2e955533e4591b335c to your computer and use it in GitHub Desktop.
Benchmark to compare hash, OpenStruct, struct, and classes in Ruby
This file contains hidden or 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 | |
def initialize(name:, email:) | |
@name = name | |
@email = email | |
end | |
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 | |
OpenStruct.new(name: NAME, email: EMAIL) | |
end | |
end | |
x.report("struct:") do | |
PersonStruct = Struct.new(:name, :email) | |
COUNT.times do | |
PersonStruct.new(name: NAME, email: EMAIL) | |
end | |
end | |
x.report("class:") do | |
COUNT.times do | |
Person.new(name: NAME, email: EMAIL) | |
end | |
end | |
end | |
user system total real | |
hash: 1.310324 0.000000 1.310324 ( 1.313880) | |
openstruct: 6.497740 0.002865 6.500605 ( 6.514609) | |
struct: 3.147043 0.000004 3.147047 ( 3.154298) | |
class: 5.571384 0.000000 5.571384 ( 5.583647) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment