gitee.com/go-genie/sqlx@v1.0.3/scanner/struct_test.go (about)

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