Reputation: 177
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
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
Without using go func avg time complexity is 22ms
With using go func avg time complexity is 427ns
Is the above approach a good practise for db operation?
Upvotes: 1
Views: 302
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