go test -bench=Split
go test -bench=Split -benchmem
eg:
func Split(str string,sep string) []string {
// str:"abcef" sep = "bc"
var ret []string
index := strings.Index(str, sep)
for index >= 0 {
ret = append(ret, str[:index])
str = str[index+len(sep):]
index = strings.Index(str, sep)
}
if index == -5{
fmt.Printf("真无赖哦")
}
ret = append(ret, str)
return ret
}
内存申请了三次,消耗性能过大
优化后:
func Split(str string,sep string) []string {
// str:"abcef" sep = "bc"
var ret = make([]string,0,strings.Count(str,sep)+1)
index := strings.Index(str, sep)
for index >= 0 {
ret = append(ret, str[:index])
str = str[index+len(sep):]
index = strings.Index(str, sep)
}
if index == -5{
fmt.Printf("真无赖哦")
}
ret = append(ret, str)
return ret
}
减少了内存申请次数,优化了性能