chore: improve snakeCasedName performance #1688

Merged
lunny merged 3 commits from performance into master 2 years ago
  1. 20
      names/mapper.go
  2. 11
      names/mapper_test.go

20
names/mapper.go

@ -7,6 +7,7 @@ package names @@ -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
@ -77,19 +78,24 @@ func (m SameMapper) Table2Obj(t string) string { @@ -77,19 +78,24 @@ func (m SameMapper) Table2Obj(t string) string {
type SnakeMapper struct {
}
func b2s(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func snakeCasedName(name string) string {
newstr := make([]rune, 0)
for idx, chr := range name {
if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
if idx > 0 {
newstr := make([]byte, 0, len(name)+1)
for i := 0; i < len(name); i++ {
c := name[i]
if isUpper := 'A' <= c && c <= 'Z'; isUpper {
if i > 0 {
newstr = append(newstr, '_')
}
chr -= ('A' - 'a')
c += 'a' - 'A'
}
newstr = append(newstr, chr)
newstr = append(newstr, c)
}
return string(newstr)
return b2s(newstr)
}
func (mapper SnakeMapper) Obj2Table(name string) string {
Review

Done

Done

11
names/mapper_test.go

@ -5,6 +5,7 @@ @@ -5,6 +5,7 @@
package names
import (
"strings"
"testing"
)
@ -47,3 +48,13 @@ func TestGonicMapperToObj(t *testing.T) { @@ -47,3 +48,13 @@ 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)
}
}

Loading…
Cancel
Save