From cc74a8854a1a42919a9650cfe280d015d9374a1a Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Thu, 21 May 2020 21:00:33 +0800 Subject: [PATCH] chore: improve snakeCasedName performance --- names/mapper.go | 21 +++++++++++++++++++++ names/mapper_test.go | 21 +++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/names/mapper.go b/names/mapper.go index 4aaf0844..b720479e 100644 --- a/names/mapper.go +++ b/names/mapper.go @@ -7,6 +7,7 @@ package names import ( "strings" "sync" + "unsafe" ) // Mapper represents a name convertation between struct's fields name and table's column name @@ -92,6 +93,26 @@ func snakeCasedName(name string) string { return string(newstr) } +func b2s(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} + +func snakeCasedNameNew(name string) string { + newstr := make([]byte, 0) + for i := 0; i < len(name); i++ { + c := name[i] + if isUpper := 'A' <= c && c <= 'Z'; isUpper { + if i > 0 { + newstr = append(newstr, '_') + } + c += 'a' - 'A' + } + newstr = append(newstr, c) + } + + return b2s(newstr) +} + func (mapper SnakeMapper) Obj2Table(name string) string { return snakeCasedName(name) } diff --git a/names/mapper_test.go b/names/mapper_test.go index 0edfd2a8..6945b84c 100644 --- a/names/mapper_test.go +++ b/names/mapper_test.go @@ -5,6 +5,7 @@ package names import ( + "strings" "testing" ) @@ -47,3 +48,23 @@ func TestGonicMapperToObj(t *testing.T) { } } } + +func BenchmarkSnakeCasedName(b *testing.B) { + b.ReportAllocs() + b.ResetTimer() + + s := strings.Repeat("FooBar", 32) + for i := 0; i < b.N; i++ { + _ = snakeCasedName(s) + } +} + +func BenchmarkSnakeCasedNameNew(b *testing.B) { + b.ReportAllocs() + b.ResetTimer() + + s := strings.Repeat("FooBar", 32) + for i := 0; i < b.N; i++ { + _ = snakeCasedNameNew(s) + } +}