美文网首页golang研究所
go预处理对性能的影响

go预处理对性能的影响

作者: 百里江山 | 来源:发表于2020-04-07 10:58 被阅读0次

表的结构,参考:https://www.jianshu.com/p/fa93ba8f865e

sql使用带占位符或不带占位符的测试

见a,b处代码

func QueryPrepare(db *sql.DB) (int, error) {
    const sqlText = "select age from nation where id = ?" // a. 此处?就是占位符。
    var count int
    err := db.QueryRow(sqlText, 1).Scan(&count)
    if err != nil {
        return 0, err
    }
    return count, nil
}
func QueryNonPrepare(db *sql.DB) (int, error) {
    const sqlText = "select age from nation where id = 1" // b. 直接使用值,而非占位符。
    var count int
    err := db.QueryRow(sqlText).Scan(&count)
    if err != nil {
        return 0, err
    }
    return count, nil
}

基准压测代码

DB是数据库句柄。

func BenchmarkQueryPrepare(b *testing.B) {
    for i := 0; i < b.N; i++ {
        QueryPrepare(DB)
    }
}
func BenchmarkQueryNonPrepare(b *testing.B) {
    for i := 0; i < b.N; i++ {
        QueryNonPrepare(DB)
    }
}

结果

go test -bench=. -benchmem

BenchmarkQueryPrepare               2936            428610 ns/op             648 B/op         21 allocs/op
BenchmarkQueryPrepare-2             2614            421596 ns/op             648 B/op         21 allocs/op
BenchmarkQueryPrepare-4             2797            412198 ns/op             648 B/op         21 allocs/op
BenchmarkQueryPrepare-8             2406            415762 ns/op             648 B/op         21 allocs/op
BenchmarkQueryNonPrepare            6015            231139 ns/op             432 B/op         13 allocs/op
BenchmarkQueryNonPrepare-2          4813            237164 ns/op             432 B/op         13 allocs/op
BenchmarkQueryNonPrepare-4          4813            250533 ns/op             432 B/op         13 allocs/op
BenchmarkQueryNonPrepare-8          4454            242844 ns/op             432 B/op         13 allocs/op

结论

非占位符性能高于占位符近似一倍

从以上基准结果来看,使用占位符与不使用占位符有明显的性能差异。
占位符之所以性能有所下降是因为需要多一次与数据库的交互,而且连接db时使用锁。

建议

  1. 占位符主要作用是防SQL注入。如登陆,必须使用注入操作。
  2. 如果普通查询,参数过滤严格,可以不使用占位符操作。这样性能更佳

参考

  1. https://www.jianshu.com/p/ee0d2e7bef54

相关文章

  • go预处理对性能的影响

    表的结构,参考:https://www.jianshu.com/p/fa93ba8f865e sql使用带占位符或...

  • 2019-06-23

    go 字符串操作性能 浅析 go 性能分析 性能分析函数

  • 探索App性能优化之绘制优化/UI流畅度优化

    一、页面绘制对App性能的影响 绘制性能主要影响 :App的页面显示速度。绘制影响性能的实质:页面的测量 & 绘制...

  • Go 性能说明

    Go 性能说明 根据 Go 开发团队和基本的算法测试,Go 语言与 C 语言的性能差距大概在 10%~20% 之间...

  • Golang 使用pprof分析性能

    参考Golang 使用pprof分析goweb的性能问题 go的pprof可以用来对服务的性能进行检测,其中net...

  • 实例数据操作02

    今天看数据预处理,其实预处理和不处理,对结果的得分有很大的影响,最好是先比较两者的差异,再决定要不要用,预处理一般...

  • Go语言·我的性能我做主(1)

    对于一些服务来说,性能是极其重要的一环,事关系统的吞吐、访问的延迟,进而影响用户的体验。 写性能测试在Go语言中是...

  • 作用域对性能的影响

    作用域对性能的影响 作用域是理解JS的关键所在,同样作用域关系到性能。其实主要还是标识符的解析会影响到性能。而我们...

  • 分析ButterKnife对性能的影响

    一 简介 ButterKnife是大神JakeWharton开源的View依赖注入框架,使用注解就可以完成View...

  • try catch 对性能影响

    来源:https://blog.csdn.net/lylwo317/article/details/5186989...

网友评论

    本文标题:go预处理对性能的影响

    本文链接:https://www.haomeiwen.com/subject/nhsgphtx.html