Skip to content

Instantly share code, notes, and snippets.

@tleish
Forked from gwilczynski/benchmark.rb
Created March 11, 2017 21:52
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 tleish/145de22fb63d6a97e04158675d62d3ec to your computer and use it in GitHub Desktop.
Save tleish/145de22fb63d6a97e04158675d62d3ec to your computer and use it in GitHub Desktop.
Please don’t hate OpenStruct
require 'benchmark'
require 'benchmark/ips'
require 'ostruct'
require 'active_model'
BillingAddressStruct = Struct.new(:street, :city, :zipcode, :country, :state)
BillingAddressOpenStruct = OpenStruct
BillingAddressStructFromHash = Struct.new(:street, :city, :zipcode, :country, :state) do
def self.from_hash(attributes)
new(*attributes.values_at(*members))
end
end
class BillingAddress
attr_accessor :street, :city, :zipcode, :country, :state
end
class BillingAddressActiveModel
include ActiveModel::Model
attr_accessor :street, :city, :zipcode, :country, :state
end
Benchmark.ips do |x|
x.report("BillingAddressStruct") do
BillingAddressStruct.new(
'Street',
'City',
'Zipcode',
'Country',
'State'
)
end
x.report("BillingAddressStructFromHash:") do
BillingAddressStructFromHash.from_hash(
street: 'Street',
city: 'City',
zipcode: 'Zipcode',
country: 'Country',
state: 'State'
)
end
x.report("BillingAddressOpenStruct") do
BillingAddressOpenStruct.new(
street: 'Street',
city: 'City',
zipcode: 'Zipcode',
country: 'Country',
state: 'State'
)
end
x.report("BillingAddress") do
BillingAddress.new.tap do |billing_address|
billing_address.street = 'Street'
billing_address.city = 'City'
billing_address.zipcode = 'Zipcode'
billing_address.country = 'Country'
billing_address.state = 'State'
end
end
x.report("BillingAddressActiveModel") do
BillingAddressActiveModel.new(
street: 'Street',
city: 'City',
zipcode: 'Zipcode',
country: 'Country',
state: 'State'
)
end
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment