使用postgres的Gorm在第一个sql上花费太长时间

nwlls2ji  于 2023-04-27  发布在  Go
关注(0)|答案(1)|浏览(177)

我正在使用Gorm和postgres驱动程序。我正在测试一些查询,发现第一个查询总是非常慢(100ms +)。我已经在MySQL测试了相同的基准测试,但没有出现这种情况。

package main

import (
    "fmt"
    "os"
    "strings"
    "time"

    "gorm.io/driver/mysql"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

var config = gorm.Config{
    PrepareStmt:            true,
    SkipDefaultTransaction: true,
}

func main() {
    dsn := "postgresql://postgres:senha123@localhost:5432/postgres?sslmode=disable"

    start := time.Now()
    db, err := gorm.Open(postgres.Open(dsn), &config)
    if err != nil {
        panic("failed to connect database")
    }

    fmt.Printf("==> Open connection: %s\n", time.Since(start))
    executeBenchmark(db)
}

func executeBenchmark(db *gorm.DB) {
    user := &User{
        Name:     "Inserted",
        Email:    "m@m.com",
        Password: "asdf",
    }

    // Test Create performance
    start := time.Now()
    db.Create(&user)
    fmt.Printf("==> Create user: %s\n", time.Since(start))

    // Test Select by email performance
    start = time.Now()
    db.Where(&User{Email: user.Email}).First(&user)
    fmt.Printf("==> Select by EMAIL user: %s\n", time.Since(start))

    // Test Update performance
    start = time.Now()
    db.Model(&user).Where(&User{ID: user.ID}).Update("name", "updated")
    fmt.Printf("==> Update user: %s\n", time.Since(start))

    // Test delete performance
    start = time.Now()
    db.Unscoped().Delete(&User{}, user.ID)
    fmt.Printf("==> Delete User user: %s\n", time.Since(start))
}

Postgres结果:

==> Open connection: 3.1902ms
==> Create user: 122.5041ms
==> Select by EMAIL user: 2.3431ms
==> Update user: 2.7019ms
==> Delete User user: 1.1994ms

如果我先执行Select by EMAIL user,它将是慢查询...
使用MySQL运行相同的基准测试:

==> Open connection: 6.2952ms
==> Create user: 8.98ms
==> Select by EMAIL user: 1.3064ms
==> Update user: 3.6067ms
==> Delete User user: 3.0996ms

去:1.20
gorm:1.25.0
驱动程序postgres:1.5.0
驱动程序MySQL:1.5.0
我想知道为什么第一个查询总是需要100ms+,以及如何改进它。请帮助=)

nnsrf1az

nnsrf1az1#

我仍然不知道为什么会发生这种情况,但我使用相同的db网络在docker容器内运行了这个基准测试,并获得了更好的结果:

==> Open connection: 336.317µs
==> Create user: 7.741506ms
==> Select by EMAIL user: 999.892µs
==> Update user: 1.034811ms
==> Delete User user: 912.888µs

第一个SQL仍然是最糟糕的,但我认为它是好的。我会假设问题是在我的本地主机与docker的东西...

相关问题