英文:
go func for db insert operation inside a for loop
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对golang还不熟悉。我已经了解了go协程(go routines),但我想知道它是否可以用于数据库插入操作。我有以下场景:
- 需要为不同类型的产品插入行。
例如:如果我有5个产品,我需要将其id、名称和创建时间插入为行。所以总共有5行对应5个产品。以下的方法是否适合使用:
for _, j := range items {
go func(j product_object){
obj := prepare_dto(j)
save_in_db(obj)
}(j)
}
我进行了试验,分别使用了带有和不带有go func的方法:
-
不使用go func的平均时间复杂度为22毫秒。
-
使用go func的平均时间复杂度为427纳秒。
上述方法是否是数据库操作的良好实践?
英文:
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
- 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
-
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?
答案1
得分: 1
是的,你可以这样做。然而,你正在对数据库进行len(items)次调用,这可能会因为连接过多而导致数据库负荷过大。在for循环中插入/更新数据库几乎总是一个不好的主意。我建议你使用批量插入,只需一次调用数据库即可。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论