Optimize Matcher.String()

Signed-off-by: Oleg Zaytsev <mail@olegzaytsev.com>
pull/14068/head
Oleg Zaytsev 7 months ago
parent dabd789fd5
commit 6ebda5a7bc
No known key found for this signature in database
GPG Key ID: 7E9FE9FD48F512EF

@ -14,7 +14,8 @@
package labels
import (
"fmt"
"strconv"
"unsafe"
)
// MatchType is an enum for label matching types.
@ -78,10 +79,20 @@ func MustNewMatcher(mt MatchType, name, val string) *Matcher {
}
func (m *Matcher) String() string {
if !m.shouldQuoteName() {
return fmt.Sprintf("%s%s%q", m.Name, m.Type, m.Value)
const quote = 1
const matcher = 2
// As we're not on go1.22 yet and we don't have the new fancy AvailableBuffer method on strings.Builder,
// we'll use a plain byte slice and then do the unsafe conversion to string just like strings.Builder does.
// We pre-allocate pessimistically for quoting the label name, and optimistically for not having to escape any quotes.
b := make([]byte, 0, quote+len(m.Name)+quote+matcher+quote+len(m.Value)+quote)
if m.shouldQuoteName() {
b = strconv.AppendQuote(b, m.Name)
} else {
b = append(b, m.Name...)
}
return fmt.Sprintf("%q%s%q", m.Name, m.Type, m.Value)
b = append(b, m.Type.String()...)
b = strconv.AppendQuote(b, m.Value)
return *((*string)(unsafe.Pointer(&b)))
}
func (m *Matcher) shouldQuoteName() bool {

Loading…
Cancel
Save