Last active
September 13, 2022 10:38
-
-
Save wroge/ab0455cf647c8abc8da4669618d9c6e3 to your computer and use it in GitHub Desktop.
Benchmark bokwoon95/sq vs wroge/scan
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update