chore: improve snakeCasedName performance

This commit is contained in:
Bo-Yi Wu 2020-05-21 21:00:33 +08:00
parent 55594d1dbe
commit cc74a8854a
2 changed files with 42 additions and 0 deletions

View File

@ -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)
}

View File

@ -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)
}
}