Skip to content

Commit

Permalink
network: don't allocate in DedupAddrs
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann committed Jun 27, 2023
1 parent acca7a6 commit da24677
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
5 changes: 3 additions & 2 deletions core/network/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import (
"bytes"
"context"
"io"
"sort"
"time"

"golang.org/x/exp/slices"

"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/peerstore"

Expand Down Expand Up @@ -203,7 +204,7 @@ func DedupAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {
if len(addrs) == 0 {
return addrs
}
sort.Slice(addrs, func(i, j int) bool { return bytes.Compare(addrs[i].Bytes(), addrs[j].Bytes()) < 0 })
slices.SortFunc(addrs, func(a, b ma.Multiaddr) bool { return bytes.Compare(a.Bytes(), b.Bytes()) < 0 })
idx := 1
for i := 1; i < len(addrs); i++ {
if !addrs[i-1].Equal(addrs[i]) {
Expand Down
11 changes: 11 additions & 0 deletions core/network/network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,14 @@ func TestDedupAddrs(t *testing.T) {
})
}
}

func BenchmarkDedupAddrs(b *testing.B) {
b.ReportAllocs()
tcpAddr := ma.StringCast("/ip4/127.0.0.1/tcp/1234")
quicAddr := ma.StringCast("/ip4/127.0.0.1/udp/1234/quic-v1")
wsAddr := ma.StringCast("/ip4/127.0.0.1/tcp/1234/ws")
addrs := []ma.Multiaddr{tcpAddr, quicAddr, tcpAddr, quicAddr, wsAddr}
for i := 0; i < b.N; i++ {
addrs = DedupAddrs(addrs)
}
}

0 comments on commit da24677

Please sign in to comment.