libnetwork/ipam: PoolID.String(): don't use fmt.Sprintf

As this function may be called repeatedly to convert to/from a string,
it may be worth optimizing it a bit. Adding a minimal Benchmark for
it as well.

Before/after:

    BenchmarkPoolIDToString-10   2842830   424.3 ns/op   232 B/op  12 allocs/op
    BenchmarkPoolIDToString-10   7176738   166.8 ns/op   112 B/op   7 allocs/op

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2023-07-22 16:10:46 +02:00
parent 87fc8c772b
commit 808fed550d
No known key found for this signature in database
GPG key ID: 76698F39D527CE8C
2 changed files with 15 additions and 4 deletions

View file

@ -1276,3 +1276,14 @@ func TestParallelPredefinedRequest4(t *testing.T) {
func TestParallelPredefinedRequest5(t *testing.T) {
runParallelTests(t, 4)
}
func BenchmarkPoolIDToString(b *testing.B) {
const poolIDString = "default/172.27.0.0/16/172.27.3.0/24"
k := PoolID{}
_ = k.FromString(poolIDString)
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = k.String()
}
}

View file

@ -45,11 +45,11 @@ type addrSpace struct {
// String returns the string form of the SubnetKey object
func (s *PoolID) String() string {
k := fmt.Sprintf("%s/%s", s.AddressSpace, s.Subnet)
if s.ChildSubnet != (netip.Prefix{}) {
k = fmt.Sprintf("%s/%s", k, s.ChildSubnet)
if s.ChildSubnet == (netip.Prefix{}) {
return s.AddressSpace + "/" + s.Subnet.String()
} else {
return s.AddressSpace + "/" + s.Subnet.String() + "/" + s.ChildSubnet.String()
}
return k
}
// FromString populates the SubnetKey object reading it from string