From 683357f2f38c3bc7f9d35ab7bbc1a91d035443c5 Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Tue, 10 Oct 2023 18:53:32 +0800 Subject: [PATCH] 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 --- src/nvm.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/nvm.go b/src/nvm.go index 7d02aed3..6f53acf0 100644 --- a/src/nvm.go +++ b/src/nvm.go @@ -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:] }