Skip to content

strings: it's logically better to use singleStringReplacer when the new string's length is 0. #33369

@anjiawei1991

Description

@anjiawei1991

if len(oldnew) == 2 && len(oldnew[0]) > 1 {
return makeSingleStringReplacer(oldnew[0], oldnew[1])
}
allNewBytes := true
for i := 0; i < len(oldnew); i += 2 {
if len(oldnew[i]) != 1 {
return makeGenericReplacer(oldnew)
}
if len(oldnew[i+1]) != 1 {
allNewBytes = false
}
}

It will make generic replacer when there's only one pair of oldnew, and the new string's length is zero. It's better to use singleStringReplacer logically, and that won't affect the performance.

as bench below:

the old:

# go test -run ^$ -bench BenchmarkSingleMatchToEmpty -count 4
goos: linux
goarch: amd64
pkg: strings
BenchmarkSingleMatchToEmpty        30000             43017 ns/op         348.69 MB/s
BenchmarkSingleMatchToEmpty        30000             42026 ns/op         356.92 MB/s
BenchmarkSingleMatchToEmpty        30000             41708 ns/op         359.64 MB/s
BenchmarkSingleMatchToEmpty        30000             42200 ns/op         355.44 MB/s

the new:

# go test -run ^$ -bench BenchmarkSingleMatchToEmpty -count 4
goos: linux
goarch: amd64
pkg: strings
BenchmarkSingleMatchToEmpty        30000             42260 ns/op         354.94 MB/s
BenchmarkSingleMatchToEmpty        30000             41242 ns/op         363.70 MB/s
BenchmarkSingleMatchToEmpty        30000             43471 ns/op         345.06 MB/s
BenchmarkSingleMatchToEmpty        30000             42606 ns/op         352.06 MB/s

my code :

	if len(oldnew) == 2 && len(oldnew[0]) != 1 {
		return makeSingleStringReplacer(oldnew[0], oldnew[1])
	}

	allNewBytes := true
	for i := 0; i < len(oldnew); i += 2 {
		if len(oldnew[i]) != 1 {
			return makeGenericReplacer(oldnew)
		}
		if len(oldnew[i+1]) != 1 {
			allNewBytes = false
		}
	}

benchmark:

func benchmarkSingleString(b *testing.B, pattern, text, value string) {
	r := NewReplacer(pattern, value)
	b.SetBytes(int64(len(text)))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		r.Replace(text)
	}
}

func BenchmarkSingleMatchToEmpty(b *testing.B) {
	benchmarkSingleString(b, "abcdef", Repeat("abcdefghijklmno", 1000), "")
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.Performance

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions