Skip to content

Commit

Permalink
Optimize GetControllerName for CNP.
Browse files Browse the repository at this point in the history
Use strings.Builder instead of fmt.Sprintf().

Results:
```
benchmark                            old ns/op     new ns/op     delta
BenchmarkCNPGetControllerName-10     338           206           -39.05%

benchmark                            old allocs     new allocs     delta
BenchmarkCNPGetControllerName-10     6              4              -33.33%

benchmark                            old bytes     new bytes     delta
BenchmarkCNPGetControllerName-10     464           432           -6.90%
```

Signed-off-by: Marcel Zieba <marcel.zieba@isovalent.com>
  • Loading branch information
marseel committed Feb 27, 2023
1 parent 984f5bd commit 929421c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
10 changes: 9 additions & 1 deletion pkg/k8s/apis/cilium.io/v2/cnp_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package v2
import (
"fmt"
"reflect"
"strings"

v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand Down Expand Up @@ -238,7 +239,14 @@ func (r *CiliumNetworkPolicy) Parse() (api.Rules, error) {
// GetControllerName returns the unique name for the controller manager.
func (r *CiliumNetworkPolicy) GetControllerName() string {
name := k8sUtils.GetObjNamespaceName(&r.ObjectMeta)
return fmt.Sprintf("%s (v2 %s)", k8sConst.CtrlPrefixPolicyStatus, name)
const staticLen = 6
var str strings.Builder
str.Grow(staticLen + len(name) + len(k8sConst.CtrlPrefixPolicyStatus))
str.WriteString(k8sConst.CtrlPrefixPolicyStatus)
str.WriteString(" (v2 ")
str.WriteString(name)
str.WriteString(")")
return str.String()
}

// GetIdentityLabels returns all rule labels in the CiliumNetworkPolicy.
Expand Down
33 changes: 33 additions & 0 deletions pkg/k8s/apis/cilium.io/v2/cnp_types_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium

package v2

import (
"testing"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func BenchmarkCNPGetControllerName(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, s := range []CiliumNetworkPolicy{
{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "default",
},
},
{
ObjectMeta: metav1.ObjectMeta{
Name: "longname",
Namespace: "",
},
},
} {
_ = s.GetControllerName()
}
}
}

0 comments on commit 929421c

Please sign in to comment.