Skip to content

Commit

Permalink
identify: use zero-alloc slice sorting function (#2396)
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann authored Jun 28, 2023
1 parent 173fef8 commit ff3bd57
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 9 deletions.
5 changes: 2 additions & 3 deletions p2p/protocol/identify/id.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"errors"
"fmt"
"io"
"sort"
"sync"
"time"

Expand Down Expand Up @@ -557,9 +556,9 @@ func readAllIDMessages(r pbio.Reader, finalMsg proto.Message) error {

func (ids *idService) updateSnapshot() (updated bool) {
addrs := ids.Host.Addrs()
sort.Slice(addrs, func(i, j int) bool { return bytes.Compare(addrs[i].Bytes(), addrs[j].Bytes()) == -1 })
slices.SortFunc(addrs, func(a, b ma.Multiaddr) bool { return bytes.Compare(a.Bytes(), b.Bytes()) == -1 })
protos := ids.Host.Mux().Protocols()
sort.Slice(protos, func(i, j int) bool { return protos[i] < protos[j] })
slices.Sort(protos)
snapshot := identifySnapshot{
addrs: addrs,
protocols: protos,
Expand Down
9 changes: 3 additions & 6 deletions p2p/protocol/identify/obsaddr.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package identify
import (
"context"
"fmt"
"sort"
"sync"
"time"

"golang.org/x/exp/slices"

"github.com/libp2p/go-libp2p/core/event"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
Expand Down Expand Up @@ -213,14 +214,10 @@ func (oas *ObservedAddrManager) filter(observedAddrs []*observedAddr) []ma.Multi

// We prefer inbound connection observations over outbound.
// For ties, we prefer the ones with more votes.
sort.Slice(s, func(i int, j int) bool {
first := s[i]
second := s[j]

slices.SortFunc(s, func(first, second *observedAddr) bool {
if first.numInbound > second.numInbound {
return true
}

return len(first.seenBy) > len(second.seenBy)
})

Expand Down

0 comments on commit ff3bd57

Please sign in to comment.