Skip to content

Commit

Permalink
Avoid unnecessary byte/string conversion
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
Juneezee committed Oct 10, 2023
1 parent 71713ec commit 683357f
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/nvm.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -529,7 +529,7 @@ func versionNumberFrom(version string) string {
}
}

for reg.Match([]byte(version[:1])) {
for reg.MatchString(version[:1]) {
version = version[1:]
}

Expand Down

0 comments on commit 683357f

Please sign in to comment.