简体   繁体   中英

Multiple transactions for a database save or a single bulk save

Looking for recommendations / opinions on this one. Do you think its better to save all the items in a single database transaction, or to save each item in its own transaction, the items have sub items etc... so they need to be saved in a transaction but the entire group/list does not. Almost everyone I would assume would just do a bulk save but I was curious. Sample pseudo code below for each.

Single Transaction:

    BeginTransaction()

    for (int i = 0; i < items.Count; i++)
        items[i].Save();

    CommitTransaction()
    
    

Multiple Transactions:

    for (int i = 0; i < items.Count; i++)
    {
      BeginTransaction()
      items[i].Save();
      CommitTransaction() 
    }
       

This is probably determined better by the requirements of what happens when one of those transactions fails. If the transactions are related and they should all fail, then put the transaction outside of the loop. If they are discrete transactions, and one failing shouldn't fail the others, put them inside the loop (and catch the failure and continue or break as appropriate).

If that doesn't matter, and you're strictly interested in a performance perspective, transactions do add overhead. How much slower is a function of a great number of variables, including the individual query size and performance, database type and configuration, and hardware/virtualization resources. It could be trivial/unmeasurable for slow queries (where the query itself takes the bulk of the time) or very large (for trivial queries).

How much is up to you to measure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM