Make ActiveRecord Faster

ActiveRecord is a wrapper around your data. By definition that should take memory, and oh indeed it does. It turns out the overhead is quite significant, in both the number of objects and in raw memory.

To see the overhead, let’s create a database table with 10 string columns and fill it with 10,000 rows, each row containing 10 strings of 100 chars.

chp3/app/db/migrate/20140722140429_large_tables.rb
 
class​ LargeTables < ActiveRecord::Migration
 
def​ up
 
create_table :things ​do​ |t|
 
10.times ​do​ |i|
 
t.string ​"col​#{i}​"
 
end
 
end
 
 
execute ​<<-END
 
insert into things(col0, col1, col2, col3, col4,
 
col5, col6, col7, col8, col9) (
 
select
 
rpad('x', 100, 'x'), rpad('x', 100, 'x'), rpad('x', ...

Get Ruby Performance Optimization now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.