I was reading Agile Web Development With Rails, when I saw this piece of code:
Order.transaction do (1..100).each do |i|
Order.create(:name => "Customer #{i}", :address => "#{i} Main Street",
:email => "customer-#{i}@example.com", :pay_type => "Check")
end end
The author said: “Note that this code does all this work in one transaction. This isn’t precisely required for this activity but does speed up the processing”.
So my question is, why the transaction speed up the processing of this block of code ?
In both cases your rails apps makes 100 separate INSERT statements, but if you don’t explicitly create a transaction then each update/insert sits inside its own transaction. Transactions are supposed to be ACID, in particular the D stands for durable: once a transaction has been committed there is a hard guarantee that it has been successfully written to disk, even if a power failure occurs 1 nanosecond later.
Committing a transaction thus requires that the writes be flushed which has an inherent cost (this can be mitigated by the right kind of RAID hardware). On the other hand when you are in the middle of one big transaction the database has no obligation to flush writes after the individual inserts.