github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/sqlx/scanner/struct_test.go (about)

     1  package scanner_test
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	_ "unsafe"
     7  
     8  	"github.com/DATA-DOG/go-sqlmock"
     9  
    10  	"github.com/machinefi/w3bstream/pkg/depends/kit/sqlx/scanner"
    11  	"github.com/machinefi/w3bstream/pkg/depends/kit/sqlx/scanner/nullable"
    12  )
    13  
    14  func BenchmarkScanStruct(b *testing.B) {
    15  	db, mock, _ := sqlmock.New()
    16  	defer db.Close()
    17  
    18  	mockRows := mock.NewRows([]string{"f_i", "f_s"})
    19  
    20  	b.Run("Direct", func(b *testing.B) {
    21  		target := &T2{}
    22  		_ = mock.ExpectQuery("SELECT .+ from t").WillReturnRows(mockRows)
    23  
    24  		rows, _ := db.Query("SELECT f_i,f_s from t")
    25  
    26  		for i := 0; i < b.N; i++ {
    27  			mockRows.AddRow(i, "a")
    28  
    29  			cs, _ := rows.Columns()
    30  
    31  			if rows.Next() {
    32  				dest := make([]interface{}, len(cs))
    33  				crs := target.ColumnReceivers()
    34  				for i := range cs {
    35  					dest[i] = nullable.NewNullIgnoreScanner(crs[cs[i]])
    36  				}
    37  				_ = rows.Scan(dest...)
    38  			}
    39  		}
    40  
    41  		b.Log(target)
    42  	})
    43  
    44  	b.Run("ScanByReflect", func(b *testing.B) {
    45  		target := &T{}
    46  		_ = mock.ExpectQuery("SELECT .+ from t").WillReturnRows(mockRows)
    47  
    48  		rows, _ := db.Query("SELECT f_i,f_s from t")
    49  
    50  		for i := 0; i < b.N; i++ {
    51  			mockRows.AddRow(i, "b")
    52  
    53  			if rows.Next() {
    54  				_ = scanner.ScanRows(context.Background(), rows, target)
    55  			}
    56  		}
    57  
    58  		b.Log(target)
    59  	})
    60  
    61  	b.Run("ScanByColumnReceivers", func(b *testing.B) {
    62  		target := &T2{}
    63  		_ = mock.ExpectQuery("SELECT .+ from t").WillReturnRows(mockRows)
    64  
    65  		rows, _ := db.Query("SELECT f_i,f_s from t")
    66  
    67  		for i := 0; i < b.N; i++ {
    68  			mockRows.AddRow(i, "c")
    69  
    70  			if rows.Next() {
    71  				_ = scanner.ScanRows(context.Background(), rows, target)
    72  			}
    73  		}
    74  
    75  		b.Log(target)
    76  	})
    77  }