Read more

ActiveRecord: Creating many records works faster in a transaction

Henning Koch
March 17, 2011Software engineer at makandra GmbH

When you need to insert many records into the same table, performance may become an issue.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

What you can do to save time is to open a transaction and save multiple records within that transaction:

transaction do
  500.times { Model.create! }
end

Although you will still trigger 500 INSERT statements, they will complete considerably faster.

When I tried it out with a simple model and 500 iterations, the loop completed in 1.5 seconds vs. 6 seconds without a transaction.

Alternative

Another fast way to insert many records is to have a single INSERT statement describing multiple rows Show archive.org snapshot .

In Rails 6+ you can do so with ActiveRecord::Base.insert_all Show archive.org snapshot . This is very fast, but you won't get the usual guarantees from validations or transactions.

Posted by Henning Koch to makandra dev (2011-03-17 14:11)