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. :)

I sense a series on ActiveRecord optimizations upon us. Today lets look at how we can test the insert of an ActiveRecord object into our database.   require "benchmark"   Benchmark.bm(7) do |x| x.report { (1..10000).each_slice(100) { |a| a.each_with_index {|p, idx| Product.create!(title: "Shoe-#{idx}", store_id: 1) }}} x.report { (1..10000).each_with_index { |p, idx| Product.create!(title: "Shoe-#{idx}", store_id: 1) } } x.report { (1..10000).each { |i| Product.create!(title: "Shoe-#{i}", store_id: 1) } } end   #=> [   #<Benchmark::Tms:0x007fa71863ed60 @label="", @real=24.679326, @cstime=0.0, @cutime=0.0, @stime=4.780000000000001, @utime=16.759999999999998, @total=21.54>,   #<Benchmark::Tms:0x007fa719869418 @label="", @real=24.60898, @cstime=0.0, @cutime=0.0, @stime=4.76, @utime=16.750000000000007, @total=21.510000000000005>,   #<Benchmark::Tms:0x007fa7162f8658 @label="", @real=24.802445, @cstime=0.0, @cutime=0.0, @stime=4.75, @utime=16.92, @total=21.67>   ] Our benchmarks around the Array show us the looping isn’t the issue (reducing the loops doesn’t have a[…]

This tidbit found in Rails source today is interesting for PostgreSQL. We can’t create anything on a table in a transaction once we break the insert for PostgreSQL. # *Warning*: one should not catch <tt>ActiveRecord::StatementInvalid</tt> exceptions # inside a transaction block. <tt>ActiveRecord::StatementInvalid</tt> exceptions indicate that an # error occurred at the database level, for example when a unique constraint # is violated. On some database systems, such as PostgreSQL, database errors # inside a transaction cause the entire transaction to become unusable # until it’s restarted from the beginning. Here is an example which # demonstrates the problem: # # # Suppose that we have a Number model with a unique column called ‘i’. # Number.transaction do # Number.create(i: 0)[…]