Skip to content

Instantly share code, notes, and snippets.

@ajayk
Created January 5, 2025 07:36
Show Gist options
  • Save ajayk/869fedfbcdb0a64444858c14de7c7a31 to your computer and use it in GitHub Desktop.
Save ajayk/869fedfbcdb0a64444858c14de7c7a31 to your computer and use it in GitHub Desktop.
package main
import (
"regexp"
"testing"
)
var testString = "abcdef1234567890ABCDEF"
// Original: Dynamic Regex Compilation
func matchValidShaCharsDynamic(s string) bool {
match, _ := regexp.MatchString("^[a-fA-F0-9]+$", s)
return match
}
// Optimized: Precompiled Regex
var validShaCharsRegex = regexp.MustCompile("^[a-fA-F0-9]+$")
func matchValidShaCharsPrecompiled(s string) bool {
return validShaCharsRegex.MatchString(s)
}
// Optimized: Manual Character Check
func matchValidShaCharsManual(s string) bool {
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F') {
return false
}
}
return true
}
func BenchmarkMatchValidShaCharsDynamic(b *testing.B) {
for i := 0; i < b.N; i++ {
matchValidShaCharsDynamic(testString)
}
}
func BenchmarkMatchValidShaCharsPrecompiled(b *testing.B) {
for i := 0; i < b.N; i++ {
matchValidShaCharsPrecompiled(testString)
}
}
func BenchmarkMatchValidShaCharsManual(b *testing.B) {
for i := 0; i < b.N; i++ {
matchValidShaCharsManual(testString)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment