Sowmya Ravichandran
Sowmya Ravichandran

Reputation: 177

go func for db insert operation inside a for loop

I am new to golang. I have read about go routines. But I am wondering whether it can be used in db insert operations. I have the following scenario

  1. Need to insert rows for different types of products in each row.

Eg: If I have 5 products I need to insert its id, name, created_at as rows.So total 5 rows for 5 products.Is the following approach good to use

for _, j := range items {
   go func(j product_object){
     obj := prepare_dto(j)
     save_in_db(obj)

}(j)
}

I made a trial with and without using go func

  1. Without using go func avg time complexity is 22ms

  2. With using go func avg time complexity is 427ns

Is the above approach a good practise for db operation?

Upvotes: 1

Views: 302

Answers (1)

Jyhonn
Jyhonn

Reputation: 83

Yes, you can do it. However, you are making len(items) calls to the database, which could potentially wear down your database due to too many connections. It's almost always a bad idea to insert / update to the database within a for loop. I suggest you to do a batch insert with only one call to the database.

Upvotes: 1

Related Questions