From ba2c4621dd644e73adecc2b7c3134b73308d5473 Mon Sep 17 00:00:00 2001 From: Yuval Kohavi Date: Wed, 24 Apr 2024 15:10:47 -0400 Subject: [PATCH] faster SanitizeNameV2 (#46) --- kubeutils/util.go | 23 ++++++++++------------- kubeutils/util_test.go | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/kubeutils/util.go b/kubeutils/util.go index 5d745f0..78637aa 100644 --- a/kubeutils/util.go +++ b/kubeutils/util.go @@ -4,6 +4,7 @@ import ( "crypto/md5" "fmt" "strings" + "unicode" ) // use SanitizeNameV2 @@ -28,23 +29,19 @@ func SanitizeName(name string) string { } func SanitizeNameV2(name string) string { - name = strings.Replace(name, "*", "-", -1) - name = strings.Replace(name, "/", "-", -1) - name = strings.Replace(name, ".", "-", -1) - name = strings.Replace(name, "[", "", -1) - name = strings.Replace(name, "]", "", -1) - name = strings.Replace(name, ":", "-", -1) - name = strings.Replace(name, "_", "-", -1) - name = strings.Replace(name, " ", "-", -1) - name = strings.Replace(name, "\n", "", -1) - name = strings.Replace(name, "\"", "", -1) - name = strings.Replace(name, "'", "", -1) + name = strings.Map(func(r rune) rune { + switch r { + case '*', '/', '.', ':', '_', ' ': + return '-' + case '[', ']', '\n', '"', '\'': + return -1 + } + return unicode.ToLower(r) + }, name) if len(name) > 63 { hash := md5.Sum([]byte(name)) name = fmt.Sprintf("%s-%x", name[:31], hash) name = name[:63] } - name = strings.Replace(name, ".", "-", -1) - name = strings.ToLower(name) return name } diff --git a/kubeutils/util_test.go b/kubeutils/util_test.go index a7ddfe5..ca2891f 100644 --- a/kubeutils/util_test.go +++ b/kubeutils/util_test.go @@ -1,8 +1,11 @@ package kubeutils import ( + "time" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + "github.com/onsi/gomega/gmeasure" ) var _ = Describe("sanitize name", func() { @@ -47,4 +50,16 @@ var _ = Describe("sanitize name", func() { Entry("301a's", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-c73301b7b71679067b02cff4cdc5e70"), ) + It("SanitizeNameV2 efficiently", Serial, Label("measurement"), func() { + experiment := gmeasure.NewExperiment("Repaginating Books") + AddReportEntry(experiment.Name, experiment) + + experiment.Sample(func(idx int) { + experiment.MeasureDuration("repagination", func() { + for i := 0; i < 1000; i++ { + SanitizeNameV2("sub []_---]_9da02_--_2") + } + }) + }, gmeasure.SamplingConfig{N: 200, Duration: time.Minute}) + }) })