Avoid unnecessary byte/string conversion

We can use `(*regexp.Regexp).MatchString` instead of
`(*regexp.Regexp).Match([]byte(...))` to avoid unnecessary `[]byte`
conversions and reduce allocations.

Example benchmark:

func BenchmarkMatch(b *testing.B) {
	reg, _ := regexp.Compile("[^0-9]")

	for i := 0; i < b.N; i++ {
		if match := reg.Match([]byte("v")); !match {
			b.Fail()
		}
	}
}

func BenchmarkMatchString(b *testing.B) {
	reg, _ := regexp.Compile("[^0-9]")

	for i := 0; i < b.N; i++ {
		if match := reg.MatchString("v"); !match {
			b.Fail()
		}
	}
}

BenchmarkMatch-16          	19712776	        65.47 ns/op	       1 B/op	       1 allocs/op
BenchmarkMatchString-16    	24261463	        51.16 ns/op	       0 B/op	       0 allocs/op

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun
2023-10-10 18:53:32 +08:00
parent 71713ecc75
commit 683357f2f3

View File

@@ -511,7 +511,7 @@ func uninstall(version string) {
func versionNumberFrom(version string) string {
reg, _ := regexp.Compile("[^0-9]")
if reg.Match([]byte(version[:1])) {
if reg.MatchString(version[:1]) {
if version[0:1] != "v" {
url := web.GetFullNodeUrl("latest-" + version + "/SHASUMS256.txt")
content := strings.Split(web.GetRemoteTextFile(url), "\n")[0]
@@ -529,7 +529,7 @@ func versionNumberFrom(version string) string {
}
}
for reg.Match([]byte(version[:1])) {
for reg.MatchString(version[:1]) {
version = version[1:]
}