datreeio / datree

Prevent Kubernetes misconfigurations from reaching production (again 😤 )! From code to cloud, Datree provides an E2E policy enforcement solution to run automatic checks for rule violations. See our docs: https://hub.datree.io
https://datree.io
Apache License 2.0
6.4k stars 359 forks source link

perf(httpClient): compare strings with `strings.EqualFold` #962

Closed Juneezee closed 1 year ago

Juneezee commented 1 year ago

Comparing two strings to the same case with strings.ToLower is more computational expensive than strings.EqualFold.

Sample benchmark:

package httpClient_test

import (
    "strings"
    "testing"
)

func BenchmarkToLower(b *testing.B) {
    for i := 0; i < b.N; i++ {
        if strings.ToLower("CONTENT-TYPE") != strings.ToLower("content-type") {
            b.Fail()
        }
    }
}

func BenchmarkEqualFold(b *testing.B) {
    for i := 0; i < b.N; i++ {
        if !strings.EqualFold("CONTENT-TYPE", "content-type") {
            b.Fail()
        }
    }
}

Result:

goos: linux
goarch: amd64
pkg: github.com/datreeio/datree/pkg/httpClient
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkToLower-16          8183317           192.1 ns/op        16 B/op          1 allocs/op
BenchmarkEqualFold-16       82634701            12.92 ns/op        0 B/op          0 allocs/op
PASS
ok      github.com/datreeio/datree/pkg/httpClient   4.181s

Reference: https://staticcheck.dev/docs/checks/#SA6005