Skip to content

Instantly share code, notes, and snippets.

@skatkov
Forked from palexander/ruby_data_object_comparison.rb
Last active September 17, 2020 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skatkov/c32ffff81dc22e2e955533e4591b335c to your computer and use it in GitHub Desktop.
Save skatkov/c32ffff81dc22e2e955533e4591b335c 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
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