Created
March 20, 2023 10:02
-
-
Save prdanelli/1e474719759c2b35edf39dabc48258ca to your computer and use it in GitHub Desktop.
Benchmark OpenStruct
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 'benchmark' | |
require 'dry-struct' | |
require 'ostruct' | |
require 'hashie' | |
require 'active_support' | |
class ClassCar | |
attr_accessor :wheels, :mileage | |
end | |
car_struct = Struct.new(:wheels, :mileage) | |
module Types | |
include Dry.Types() | |
end | |
class DryCar < Dry::Struct | |
attribute :wheels, Types::Integer | |
attribute :mileage, Types::Integer | |
end | |
iterations = 250_000 | |
Benchmark.bmbm(10) do |b| | |
b.report("OStruct") do | |
items = [] | |
iterations.times do | |
car = OpenStruct.new | |
car.wheel = 4 | |
car.mileage = rand((1..100)) | |
items << car | |
end | |
items.each { |item| item.mileage } | |
end | |
b.report("Class") do | |
items = [] | |
iterations.times do | |
car = ClassCar.new | |
car.wheels = 4 | |
car.mileage = rand((1..100)) | |
items << car | |
end | |
items.each { |item| item.mileage } | |
end | |
b.report("Struct") do | |
items = [] | |
iterations.times do | |
items << car_struct.new(4, rand((1..100))) | |
end | |
items.each { |item| item.mileage } | |
end | |
b.report("OrderedOptions") do | |
items = [] | |
iterations.times do | |
car = ActiveSupport::OrderedOptions.new | |
car.wheels = 4 | |
car.mileage = rand((1..100)) | |
items << car | |
end | |
items.each { |item| item.mileage } | |
end | |
b.report("Hash") do | |
items = [] | |
iterations.times do | |
items << { wheels: 4, mileage: rand((1..100)) } | |
end | |
items.each { |item| item[:mileage] } | |
end | |
b.report("DryStruct") do | |
items = [] | |
iterations.times do | |
items << DryCar.new(wheels: 4, mileage: rand((1..100))) | |
end | |
items.each { |item| item.mileage } | |
end | |
b.report("Hashie") do | |
items = [] | |
iterations.times do | |
items << Hashie::Mash.new(wheels: 4, mileage: rand((1..100))) | |
end | |
items.each { |item| item.mileage } | |
end | |
items = [] | |
b.report("Array") do | |
iterations.times do | |
items << [4, rand((1..100))] | |
end | |
items.each { |item| item[1] } | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment