chore: improve snakeCasedName performance #1688

Merged
lunny merged 3 commits from performance into master 2020-05-22 02:54:50 +00:00
2 changed files with 42 additions and 0 deletions
Showing only changes of commit cc74a8854a - Show all commits

@ -7,6 +7,7 @@ package names
import ( import (
"strings" "strings"
"sync" "sync"
"unsafe"
) )
// Mapper represents a name convertation between struct's fields name and table's column name // 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) 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 { func (mapper SnakeMapper) Obj2Table(name string) string {
return snakeCasedName(name) return snakeCasedName(name)
} }

@ -5,6 +5,7 @@
package names package names
import ( import (
"strings"
"testing" "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)
}
}