Skip to content

Instantly share code, notes, and snippets.

@wroge
Last active September 13, 2022 10:38
Show Gist options
  • Select an option

  • Save wroge/ab0455cf647c8abc8da4669618d9c6e3 to your computer and use it in GitHub Desktop.

Select an option

Save wroge/ab0455cf647c8abc8da4669618d9c6e3 to your computer and use it in GitHub Desktop.
Benchmark bokwoon95/sq vs wroge/scan
package main_test
import (
"database/sql"
"encoding/json"
"testing"
"github.com/bokwoon95/sq"
"github.com/wroge/scan"
)
type Author struct {
ID int64
Name string
}
type Post struct {
ID int64
Title string
Authors []Author
}
var (
result []Post
query = `WITH posts(id, title, authors) AS (VALUES
(1, 'Post One', JSON_ARRAY(JSON_OBJECT('id', 1, 'name', 'Jim'), JSON_OBJECT('id', 2, 'name', 'Tim'))),
(2, 'Post Two', JSON_ARRAY(JSON_OBJECT('id', 2, 'name', 'Tim'))))
SELECT * FROM posts`
)
func BenchmarkBokwoon95Sq(b *testing.B) {
var (
posts []Post
err error
)
db, _ := sql.Open("sqlite", ":memory:")
b.ResetTimer()
for n := 0; n < b.N; n++ {
posts, err = sq.FetchAll(db, sq.
Queryf(query).
SetDialect(sq.DialectSQLite),
func(row *sq.Row) (Post, error) {
var post Post
post.ID = row.Int64("posts.id")
post.Title = row.String("posts.title")
row.JSON(&post.Authors, "posts.authors")
return post, nil
},
)
if err != nil {
b.Error(err)
}
result = posts
}
}
func BenchmarkWrogeScan(b *testing.B) {
var (
rows scan.Rows
posts []Post
err error
)
db, _ := sql.Open("sqlite", ":memory:")
b.ResetTimer()
for n := 0; n < b.N; n++ {
rows, err = db.Query(query)
if err != nil {
b.Error(err)
}
posts, err = scan.All[Post](rows,
scan.Any(func(post *Post, id int64) { post.ID = id }),
scan.Any(func(post *Post, title string) { post.Title = title }),
scan.AnyErr(func(post *Post, authors []byte) error { return json.Unmarshal(authors, &post.Authors) }),
)
if err != nil {
b.Error(err)
}
result = posts
}
}
@wroge
Copy link
Author

wroge commented Sep 13, 2022

Update

➜ go test -bench=. -benchtime=10s -benchmem
goos: darwin
goarch: amd64
pkg: test
cpu: Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz
BenchmarkBokwoon95Sq-8            192770             55865 ns/op            3762 B/op         82 allocs/op
BenchmarkWrogeScan-8              239088             53190 ns/op            1776 B/op         56 allocs/op
PASS
ok      test    24.648s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment