Skip to content

Instantly share code, notes, and snippets.

@c80609a
Forked from solnic/am_dry_validation_1.rb
Created December 11, 2018 14:51
Show Gist options
  • Save c80609a/f9326ac3169f335fb10e71be7714bb38 to your computer and use it in GitHub Desktop.
Save c80609a/f9326ac3169f335fb10e71be7714bb38 to your computer and use it in GitHub Desktop.
dry-validation vs activemodel
require 'benchmark/ips'
require 'active_model'
require 'virtus'
require 'dry-validation'
require 'dry/validation/schema/form'
class User
include ActiveModel::Validations
include Virtus.model
attribute :email, String
attribute :age, Integer
validates :email, :age, presence: true
validates :age, numericality: { greater_than: 18 }
end
class UserFormSchema < Dry::Validation::Schema::Form
key(:email) { |value| value.filled? }
key(:age) { |value| value.int? & value.gt?(18) }
end
schema = UserFormSchema.new
params = { 'email' => '', 'age' => '18' }
Benchmark.ips do |x|
x.report('ActiveModel::Validations + Virtus') do
User.new(params).validate
end
x.report('dry-validation') do
schema.(params)
end
x.compare!
end
require 'benchmark/ips'
require 'active_model'
require 'virtus'
require 'dry-validation'
require 'dry/validation/schema/form'
class User
include ActiveModel::Validations
attr_reader :email, :age
validates :email, :age, presence: true
validates :age, numericality: { greater_than: 18 }
def initialize(attrs)
@email, @age = attrs.values_at('email', 'age')
end
end
class UserFormSchema < Dry::Validation::Schema::Form
key(:email) { |value| value.filled? }
key(:age) { |value| value.int? & value.gt?(18) }
end
schema = UserFormSchema.new
params = { 'email' => '', 'age' => '18' }
Benchmark.ips do |x|
x.report('ActiveModel::Validations') do
User.new(params).validate
end
x.report('dry-validation') do
schema.messages(params)
end
x.compare!
end
Calculating -------------------------------------
ActiveModel::Validations + Virtus
145.000 i/100ms
dry-validation 6.527k i/100ms
-------------------------------------------------
ActiveModel::Validations + Virtus
1.499k (± 2.6%) i/s - 7.540k
dry-validation 71.432k (± 2.9%) i/s - 358.985k
Comparison:
dry-validation: 71431.6 i/s
ActiveModel::Validations + Virtus: 1499.3 i/s - 47.64x slower
Calculating -------------------------------------
ActiveModel::Validations
169.000 i/100ms
dry-validation 2.417k i/100ms
-------------------------------------------------
ActiveModel::Validations
1.723k (± 3.0%) i/s - 8.619k
dry-validation 25.298k (± 3.5%) i/s - 128.101k
Comparison:
dry-validation: 25298.0 i/s
ActiveModel::Validations: 1723.2 i/s - 14.68x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment