Created
March 2, 2017 23:23
-
-
Save gwilczynski/f402aa8aed496da16af5cd2cd9cbe822 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) | |
instance = new | |
attributes.each do |key, value| | |
instance[key] = value | |
end | |
instance | |
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
A more compact version of the BillingAddressStructFromHash with same performance if interested