Skip to content

Instantly share code, notes, and snippets.

@joevandyk
Last active August 29, 2015 14:08
Show Gist options
  • Save joevandyk/e73a730a10198d01bc4a to your computer and use it in GitHub Desktop.
Save joevandyk/e73a730a10198d01bc4a to your computer and use it in GitHub Desktop.
require 'active_record'
require 'pg'
require 'benchmark'
require 'sequel'
ActiveRecord::Base.establish_connection("postgres://localhost/test")
DB = Sequel.connect('postgres://localhost/test')
ActiveRecord::Base.connection.execute <<-SQL
drop table t1 cascade; drop table t2 cascade; drop table t3 cascade;
create table t1 (
id serial primary key,
name text not null
);
create table t2 (
name text
);
create table t3 (
name text
);
create or replace function make_t3() returns trigger as $$ begin
insert into t3 (name) values (new.name);
insert into t3 (name) values (new.name);
return new;
end $$ language plpgsql;
create trigger t3 after insert on t2 for each row execute procedure make_t3();
SQL
class T1 < ActiveRecord::Base
self.table_name = :t1
after_create :make_t3
def make_t3
T3.create!(name: self.name)
T3.create!(name: self.name)
end
end
class T3 < ActiveRecord::Base
self.table_name = :t3
end
# Using ActiveRecord to handle the after create's
puts(Benchmark.measure("t1") { 5000.times { T1.create!(name: 'joe') } })
# 5.300000 0.330000 5.630000 ( 8.885517)
# Using triggers and no ORMs
puts(Benchmark.measure("t2") { 5000.times { DB[:t2].insert(name: 'joe') } })
# 0.330000 0.190000 0.520000 ( 0.998176)
# Think about how many ActiveRecord objects your tests and application code make.
# Worth the 800% overhead? Maybe not on write-heavy applications.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment