Skip to content

Instantly share code, notes, and snippets.

@solnic
Last active December 10, 2015 13:30
Show Gist options
  • Save solnic/854e6348bc015b2fad82 to your computer and use it in GitHub Desktop.
Save solnic/854e6348bc015b2fad82 to your computer and use it in GitHub Desktop.
Type-safe struct with constraints vs ActiveRecord instantiation
require 'dry-data'
require 'dry/data/type/constrained'
require 'active_record'
require 'benchmark/ips'
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
create_table :users do |table|
table.column :name, :string
table.column :age, :string
end
end
class ARUser < ActiveRecord::Base
self.table_name = :users
end
module Types
end
Dry::Data.configure do |config|
config.namespace = Types
end
Dry::Data.finalize
class DryDataUser < Dry::Data::Struct
attribute :id, Types::Strict::Int
attribute :name, Types::Strict::String.constrained(size: 3..64)
attribute :age, Types::Strict::Int.constrained(gt: 18)
end
Benchmark.ips do |x|
x.report('active record') { ARUser.new(id: 1, name: 'Jane', age: 21) }
x.report('dry-data') { DryDataUser.new(id: 1, name: 'Jane', age: 21) }
x.compare!
end
Calculating -------------------------------------
active record 1.563k i/100ms
dry-data 7.460k i/100ms
-------------------------------------------------
active record 16.921k (± 2.8%) i/s - 85.965k
dry-data 94.894k (± 3.6%) i/s - 477.440k
Comparison:
dry-data: 94894.1 i/s
active record: 16920.6 i/s - 5.61x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment