Skip to content

Instantly share code, notes, and snippets.

@mniewrzal
Last active June 21, 2019 09:02
Show Gist options
  • Save mniewrzal/49de3af95f36e63e88fac24f565e444c to your computer and use it in GitHub Desktop.
Save mniewrzal/49de3af95f36e63e88fac24f565e444c to your computer and use it in GitHub Desktop.
func BenchmarkValidation(b *testing.B) {
buckets := [][]byte{
[]byte("five5"),
[]byte("abcd-abcd-abcd-abcd-abcd-abcd"),
[]byte("abcd-abcd-abcd-abcd-abcd-abcd-abcd-abcd-abcd-abcd-abcd-abcd"),
}
for _, bucket := range buckets {
b.Run("simple-size-"+strconv.Itoa(len(bucket)), func(b *testing.B) {
for n := 0; n < b.N; n++ {
labels := bytes.Split(bucket, []byte("."))
for _, label := range labels {
_ = validateBucketLabel(label)
}
}
})
regexp := regexp.MustCompile(`^([a-z0-9]+([a-z0-9\-][a-z0-9])*)+(.[a-z0-9]+([a-z0-9\-][a-z0-9])*)*$`)
b.Run("regexp-size-"+strconv.Itoa(len(bucket)), func(b *testing.B) {
for n := 0; n < b.N; n++ {
regexp.MatchString(string(bucket))
}
})
}
}
func validateBucketLabel(label []byte) error {
if len(label) == 0 {
return errs.New("bucket label cannot be empty")
}
if !isLowerLetter(label[0]) && !isDigit(label[0]) {
return errs.New("bucket label must start with a lowercase letter or number")
}
if label[0] == '-' || label[len(label)-1] == '-' {
return errs.New("bucket label cannot start or end with a hyphen")
}
for i := 1; i < len(label)-1; i++ {
if !isLowerLetter(label[i]) && !isDigit(label[i]) && (label[i] != '-') && (label[i] != '.') {
return errs.New("bucket name must contain only lowercase letters, numbers or hyphens")
}
}
return nil
}
func isLowerLetter(r byte) bool {
return r >= 'a' && r <= 'z'
}
func isDigit(r byte) bool {
return r >= '0' && r <= '9'
}
@mniewrzal
Copy link
Author

Results:

BenchmarkValidation/simple-size-5-8         	30000000	        51.7 ns/op	      32 B/op	       1 allocs/op
BenchmarkValidation/regexp-size-5-8         	 5000000	       252 ns/op	       5 B/op	       1 allocs/op
BenchmarkValidation/simple-size-29-8        	20000000	       100 ns/op	      32 B/op	       1 allocs/op
BenchmarkValidation/regexp-size-29-8        	 2000000	       991 ns/op	      32 B/op	       1 allocs/op
BenchmarkValidation/simple-size-59-8        	20000000	       121 ns/op	      32 B/op	       1 allocs/op
BenchmarkValidation/regexp-size-59-8        	 1000000	      1857 ns/op	      65 B/op	       1 allocs/op
PASS
ok  	storj.io/storj/satellite/metainfo	12.664s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment