Skip to content

Instantly share code, notes, and snippets.

@mahm
Last active August 29, 2015 14:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mahm/55079450bcb2505d3fb6 to your computer and use it in GitHub Desktop.
'each commit' vs 'transaction' vs 'bulk_insert'
require 'benchmark'
def each_commit(size)
project = Project.create!(name: "each_commit #{size}")
size.times.with_index(1) do |_, index|
project.tasks.create!(name: "Task #{index}")
end
end
def transaction(size)
ActiveRecord::Base.transaction do
project = Project.create!(name: "transaction #{size}")
size.times.with_index(1) do |_, index|
project.tasks.create!(name: "Task #{index}")
end
end
end
def bulk_insert(size)
project = Project.create!(name: "bulk_insert #{size}")
tasks = (1..size).map do |index|
Task.new(name: "Task #{index}", project_id: project.id)
end
Task.import(tasks)
end
def benchmark(size)
puts "** #{size}レコードのデータを保存"
Benchmark.bm(16) do |b|
%w(each_commit transaction bulk_insert).each do |method|
b.report(method) { send(method.to_sym, size) }
end
end
end
[100, 1000, 10000].each do |record_size|
benchmark(record_size)
end
** 100レコードのデータを保存
user system total real
each_commit 0.410000 0.100000 0.510000 ( 0.570270)
transaction 0.310000 0.020000 0.330000 ( 0.322642)
bulk_insert 0.020000 0.000000 0.020000 ( 0.026268)
** 1000レコードのデータを保存
user system total real
each_commit 3.900000 0.620000 4.520000 ( 4.971859)
transaction 3.980000 0.160000 4.140000 ( 4.144867)
bulk_insert 0.230000 0.010000 0.240000 ( 0.229818)
** 10000レコードのデータを保存
user system total real
each_commit 80.330000 6.840000 87.170000 ( 91.277122)
transaction 124.760000 8.700000 133.460000 (133.544246)
bulk_insert 2.260000 0.020000 2.280000 ( 2.292815)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment