Skip to content

Instantly share code, notes, and snippets.

@solnic
Last active November 24, 2021 02:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save solnic/58fade416fe80cf18df9 to your computer and use it in GitHub Desktop.
Save solnic/58fade416fe80cf18df9 to your computer and use it in GitHub Desktop.
Fetching type-safe entity with rom repo vs AR
Calculating -------------------------------------
type-safe users 273.000 i/100ms
ar user models 257.000 i/100ms
-------------------------------------------------
type-safe users 2.813k (± 1.7%) i/s - 14.196k
ar user models 2.574k (±10.7%) i/s - 12.850k
Comparison:
type-safe users: 2812.7 i/s
ar user models: 2574.2 i/s - 1.09x slower
require 'benchmark/ips'
require 'dry-data'
require 'dry/data/type/constrained'
require 'rom-sql'
require 'rom-repository'
require 'active_record'
DB_URL = 'postgresql://localhost/rom_repository'
ActiveRecord::Base.establish_connection(DB_URL)
class User < ActiveRecord::Base
end
rom = ROM.container(:sql, DB_URL) do |config|
class Users < ROM::Relation[:sql]
end
config.register_relation(Users)
end
rom.gateways[:default].connection.execute('delete from users')
rom.relation(:users).insert(name: 'Jane')
rom.relation(:users).insert(name: 'Joe')
rom.relation(:users).insert(name: 'Jade')
module Types
end
Dry::Data.configure { |c| c.namespace = Types }
Dry::Data.finalize
module Types
PrimaryKey = Strict::Int.constrained(gt: 0)
Name = Strict::String.constrained(min_size: 3)
end
module Entities
class User < Dry::Data::Struct
attribute :id, Types::PrimaryKey
attribute :name, Types::Name
end
end
class UserRepo < ROM::Repository
relations :users
end
user_repo = UserRepo.new(rom)
users = user_repo.users.as(Entities::User)
Benchmark.ips do |x|
x.report('type-safe users') do
users.to_a
end
x.report('ar user models') do
User.all.to_a
end
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment