LoginSignup
4
4

More than 5 years have passed since last update.

Rails複数レコードのInsert方法を比較する - 通常, トランザクション, バルク

Last updated at Posted at 2017-05-11

Railsでのバルクインザートは、activerecord-importを使う。

require 'benchmark'

Benchmark.bm(10) do |r|
  r.report 'nomal' do
    users = User.limit(1000)
    users.each do |user|
      UserSomething.create(user_id: user.id, something_id: 9)
    end
  end
  r.report 'transaction' do
    users = User.limit(1000)
    ActiveRecord::Base.transaction do
      users.each do |user|
        UserSomething.create(user_id: user.id, something_id: 10)
      end
    end
  end
  r.report 'bulk' do
    user_somethings = []
    users = User.limit(1000)
    users.each do |user|
      user_somethings << UserSomething.new(user_id: user.id, something_id: 11)
    end
    UserSomething.import user_somethings
  end
end

だいぶ早い。

                 user     system      total        real
nomal        1.820000   0.090000   1.910000 (  3.077426)
transaction  1.250000   0.040000   1.290000 (  1.403902)
bulk         0.500000   0.000000   0.500000 (  0.512674)
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4