-
-
Save tleish/145de22fb63d6a97e04158675d62d3ec to your computer and use it in GitHub Desktop.
Please don’t hate OpenStruct
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 '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