chore: improve snakeCasedName performance (#1688)

chore: update

chore: udpate

chore: improve snakeCasedName performance

Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
Reviewed-on: https://gitea.com/xorm/xorm/pulls/1688
Reviewed-by: appleboy <appleboy.tw@gmail.com>
This commit is contained in:
Lunny Xiao 2020-05-22 02:53:55 +00:00
parent 55594d1dbe
commit d485101331
2 changed files with 24 additions and 7 deletions

View File

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

View File

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