Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Benchmark: shallow_attributes vs virtus
require 'benchmark/ips'
require 'shallow_attributes'
require 'virtus'
hash = {
addresses: [
{
street: 'Street 1/2',
city: {
name: 'NYC'
}
},
{
street: 'Street 3/2',
city: {
name: 'Moscow'
}
}
]
}
class City
include ShallowAttributes
attribute :name, String
attribute :size, Integer, default: 9000
end
class Address
include ShallowAttributes
attribute :street, String
attribute :zipcode, String, default: '111111'
attribute :city, City
end
class Person
include ShallowAttributes
attribute :name, String
attribute :address, Address
attribute :addresses, Array, of: Address
end
class VirtusCity
include Virtus.model
attribute :name, String
attribute :size, Integer, default: 9000
end
class VirtusAddress
include Virtus.model
attribute :street, String
attribute :zipcode, String, default: '111111'
attribute :city, VirtusCity
end
class VirtusUser
include Virtus.model
attribute :name, String
attribute :address, VirtusAddress
attribute :addresses, Array[VirtusAddress]
end
shallow_attributes = Person.new(hash)
virtus = VirtusUser.new(hash)
Benchmark.ips do |x|
x.report('Initialize: SA') { Person.new(hash) }
x.report('Initialize: virtus') { VirtusUser.new(hash) }
x.report('Getter: SA') { shallow_attributes.addresses.first.city.size }
x.report('Getter: virtus') { virtus.addresses.first.city.size }
x.report('Setter: SA') { shallow_attributes.addresses.first.city.size = '12' }
x.report('Setter: virtus') { virtus.addresses.first.city.size = '12' }
x.report('Attributes: SA') { shallow_attributes.attributes }
x.report('Attributes: virtus') { virtus.attributes }
x.report('Equals: SA') { shallow_attributes == virtus }
x.report('Equals: virtus') { virtus == shallow_attributes }
x.compare!
end
# Warming up --------------------------------------
# Initialize: SA 2.053k i/100ms
# Initialize: virtus 934.000 i/100ms
# Getter: SA 118.291k i/100ms
# Getter: virtus 34.085k i/100ms
# Setter: SA 42.493k i/100ms
# Setter: virtus 4.589k i/100ms
# Attributes: SA 44.074k i/100ms
# Attributes: virtus 18.233k i/100ms
# Equals: SA 13.352k i/100ms
# Equals: virtus 133.364k i/100ms
#
# Calculating -------------------------------------
# Initialize: SA 22.119k (± 8.2%) i/s - 110.862k
# Initialize: virtus 11.572k (±19.3%) i/s - 55.106k
#
# Getter: SA 6.470M (±14.5%) i/s - 31.347M
# Getter: virtus 755.849k (± 9.7%) i/s - 3.749M
#
# Setter: SA 635.142k (± 9.7%) i/s - 3.144M
# Setter: virtus 46.577k (± 6.5%) i/s - 234.039k
#
# Attributes: SA 534.020k (±23.0%) i/s - 2.556M
# Attributes: virtus 182.737k (±22.0%) i/s - 856.951k
#
# Equals: SA 150.006k (± 8.2%) i/s - 747.712k
# Equals: virtus 9.704M (± 5.2%) i/s - 48.411M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.