优化代码

This commit is contained in:
刘祥超
2021-12-13 15:31:03 +08:00
parent 173175a248
commit 28e93c05a2
2 changed files with 42 additions and 8 deletions

View File

@@ -31,7 +31,17 @@ func ParseVariables(source string, replacer func(varName string) (value string))
return source
}
// replace
// 只有一个占位时,我们快速返回
if len(holders) == 1 {
var h = holders[0]
holder, ok := h.(VariableHolder)
if ok {
return replacer(string(holder))
}
return source
}
// 多个占位时使用Builder
result := strings.Builder{}
for _, h := range holders {
holder, ok := h.(VariableHolder)

View File

@@ -1,17 +1,31 @@
package configutils
import (
"fmt"
"github.com/iwind/TeaGo/types"
"runtime"
"strconv"
"testing"
)
func TestParseVariables(t *testing.T) {
v := ParseVariables("hello, ${name}, world", func(s string) string {
return "Lu"
})
t.Log(v)
{
v := ParseVariables("hello, ${name}, world", func(s string) string {
return "Lu"
})
t.Log(v)
}
{
v := ParseVariables("hello, world", func(s string) string {
return "Lu"
})
t.Log(v)
}
{
v := ParseVariables("${name}", func(s string) string {
return "Lu"
})
t.Log(v)
}
}
func TestParseNoVariables(t *testing.T) {
@@ -58,7 +72,17 @@ func BenchmarkParseVariablesFromHolders(b *testing.B) {
func BenchmarkParseVariablesUnique(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = ParseVariables("hello, ${name} "+strconv.Itoa(i%1000), func(s string) string {
_ = ParseVariables("hello, ${name} "+strconv.Itoa(i), func(s string) string {
return "Lu"
})
}
}
func BenchmarkParseVariablesUnique_Single(b *testing.B) {
runtime.GOMAXPROCS(1)
for i := 0; i < b.N; i++ {
_ = ParseVariables("${name}", func(s string) string {
return "Lu"
})
}
@@ -66,7 +90,7 @@ func BenchmarkParseVariablesUnique(b *testing.B) {
func BenchmarkParseNoVariables(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = ParseVariables("hello, world, "+fmt.Sprintf("%d", i%1000), func(s string) string {
_ = ParseVariables("hello, world", func(s string) string {
return "Lu"
})
}