带有 postgres 的 Gorm 在第一个 sql 上花费的时间太长

问题描述 投票:0回答:1

我正在使用带有 postgres 驱动程序的 Gorm。我正在测试一些查询并意识到第一个查询总是很慢(100 毫秒以上)。我在 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:    "[email protected]",
        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

我想了解为什么第一个查询总是需要 100 毫秒以上,以及我如何改进它。请帮忙=)

postgresql go go-gorm
1个回答
0
投票

我仍然不知道为什么会这样,但我使用相同的数据库网络在 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还是最差的,不过我觉得还好。我假设问题出在我的 localhost 和 docker 中......

© www.soinside.com 2019 - 2024. All rights reserved.