From c7a12ca3d8b5b238d8b7fef93470b1d620b5dad1 Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Thu, 21 Mar 2024 18:46:07 +0300 Subject: [PATCH] [#1054] network: Optimize IsTLSEnabled() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit No big deal, but it is called multiple times in sorting routine, this easily results in 20 allocations per group traversal. ``` goos: linux goarch: amd64 pkg: git.frostfs.info/TrueCloudLab/frostfs-node/pkg/network cpu: 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz │ old │ new │ │ sec/op │ sec/op vs base │ AddressTLSEnabled-8 184.6n ± 1% 103.3n ± 6% -44.04% (p=0.000 n=10) │ old │ new │ │ B/op │ B/op vs base │ AddressTLSEnabled-8 704.0 ± 0% 0.0 ± 0% -100.00% (p=0.000 n=10) │ old │ new │ │ allocs/op │ allocs/op vs base │ AddressTLSEnabled-8 1.000 ± 0% 0.000 ± 0% -100.00% (p=0.000 n=10) ``` Signed-off-by: Evgenii Stratonikov --- pkg/network/tls.go | 9 ++------- pkg/network/tls_test.go | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/pkg/network/tls.go b/pkg/network/tls.go index 9aac89c47..544dc8240 100644 --- a/pkg/network/tls.go +++ b/pkg/network/tls.go @@ -13,11 +13,6 @@ var tls, _ = multiaddr.NewMultiaddr("/" + tlsProtocolName) // IsTLSEnabled searches for wrapped TLS protocol in multiaddr. func (a Address) IsTLSEnabled() bool { - for _, protoc := range a.ma.Protocols() { - if protoc.Code == multiaddr.P_TLS { - return true - } - } - - return false + _, err := a.ma.ValueForProtocol(multiaddr.P_TLS) + return err == nil } diff --git a/pkg/network/tls_test.go b/pkg/network/tls_test.go index d93ea6a12..6c352484b 100644 --- a/pkg/network/tls_test.go +++ b/pkg/network/tls_test.go @@ -27,3 +27,18 @@ func TestAddress_TLSEnabled(t *testing.T) { require.Equal(t, test.wantTLS, addr.IsTLSEnabled(), test.input) } } + +func BenchmarkAddressTLSEnabled(b *testing.B) { + var addr Address + err := addr.FromString("/dns4/localhost/tcp/8080/tls") + require.NoError(b, err) + + b.ResetTimer() + b.ReportAllocs() + + var enabled bool + for i := 0; i < b.N; i++ { + enabled = addr.IsTLSEnabled() + } + require.True(b, enabled) +}