在 Gin + GORM 项目中,批量插入性能是一个常见瓶颈,特别是当插入数据量较大时。
GORM 的 Create() 是逐条插入,CreateInBatches() 是批量插入,效率更高;原生 SQL(如 INSERT INTO ... VALUES (...), (...), (...))可以进一步优化性能。
下面是一个实际性能对比测试用例,使用 10,000 条数据进行插入,比较三种方式:
🔬 测试对比方式
gorm.Create()— 单条插入(最慢)gorm.CreateInBatches()— GORM 提供的批量插入- 原生 SQL — 自定义构造
INSERT INTO批量 SQL
🧪 测试代码
package main
import (
"fmt"
"log"
"strings"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"size:100"`
Age int
}
const (
batchSize = 500
total = 10000
)
func main() {
dsn := "root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config

最低0.47元/天 解锁文章
896

被折叠的 条评论
为什么被折叠?



