In Rails ActiveRecord objects normally take about 300 milliseconds to execute an insert. Yesterday I posted some benchmarks on looping thousands of inserts. Today lets look at how we might populate a data table faster with mass insert.

def populate_products
  products = []
  10000.times do |sku|
    products << Product.new(:title => sku, :store_id => 1)
  end
  Product.import products
end
 
puts bench = Benchmark.measure { populate_products }
 
#=>  2.680000   0.030000   2.710000 (  2.879265)

BOOM! 10,000 Skus created in under 3 seconds. This was with the help of ‘activerecord-import’. A fantastic gem which selects the right query choice for the adapter.

:)

One thought on “Daily Ruby Tips #147 – A Faster Rails Insert with Mass Insert

  1. Phuwanart Larpmark says:

    Awesome, thank for sharing your knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *