Skip to content

Commit

Permalink
Merge pull request #191 from libp2p/various-addr-book-optimizations
Browse files Browse the repository at this point in the history
optimize allocations in the memory address book
  • Loading branch information
marten-seemann authored Dec 14, 2021
2 parents b40a117 + 325d729 commit 2da8c8d
Showing 1 changed file with 3 additions and 12 deletions.
15 changes: 3 additions & 12 deletions p2p/host/peerstore/pstoremem/addr_book.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,6 @@ func (mab *memoryAddrBook) gc() {
now := time.Now()
for _, s := range mab.segments {
s.Lock()
var collectedPeers []peer.ID
for p, amap := range s.addrs {
for k, addr := range amap {
if addr.ExpiredBy(now) {
Expand All @@ -120,13 +119,9 @@ func (mab *memoryAddrBook) gc() {
}
if len(amap) == 0 {
delete(s.addrs, p)
collectedPeers = append(collectedPeers, p)
delete(s.signedPeerRecords, p)
}
}
// remove signed records for peers whose signed addrs have all been removed
for _, p := range collectedPeers {
delete(s.signedPeerRecords, p)
}
s.Unlock()
}
}
Expand Down Expand Up @@ -221,23 +216,19 @@ func (mab *memoryAddrBook) addAddrsUnlocked(s *addrSegment, p peer.ID, addrs []m
}

exp := time.Now().Add(ttl)
addrSet := make(map[string]struct{}, len(addrs))
for _, addr := range addrs {
if addr == nil {
log.Warnw("was passed nil multiaddr", "peer", p)
continue
}
k := string(addr.Bytes())
addrSet[k] = struct{}{}

// find the highest TTL and Expiry time between
// existing records and function args
a, found := amap[k] // won't allocate.

a, found := amap[string(addr.Bytes())] // won't allocate.
if !found {
// not found, announce it.
entry := &expiringAddr{Addr: addr, Expires: exp, TTL: ttl}
amap[k] = entry
amap[string(addr.Bytes())] = entry
mab.subManager.BroadcastAddr(p, addr)
} else {
// update ttl & exp to whichever is greater between new and existing entry
Expand Down

0 comments on commit 2da8c8d

Please sign in to comment.