Unverified Commit 69c28bb5 authored by Jakub Sztandera's avatar Jakub Sztandera Committed by GitHub

Merge pull request #17 from libp2p/feat/optimize-allocations

reduce the number of slice reallocations
parents f37743c9 262aab6b
......@@ -25,6 +25,11 @@ func (p peerSorterArr) Less(a, b int) bool {
//
func copyPeersFromList(target ID, peerArr peerSorterArr, peerList *list.List) peerSorterArr {
if cap(peerArr) < len(peerArr)+peerList.Len() {
newArr := make(peerSorterArr, 0, len(peerArr)+peerList.Len())
copy(newArr, peerArr)
peerArr = newArr
}
for e := peerList.Front(); e != nil; e = e.Next() {
p := e.Value.(peer.ID)
pID := ConvertPeerID(p)
......@@ -38,7 +43,7 @@ func copyPeersFromList(target ID, peerArr peerSorterArr, peerList *list.List) pe
}
func SortClosestPeers(peers []peer.ID, target ID) []peer.ID {
var psarr peerSorterArr
psarr := make(peerSorterArr, 0, len(peers))
for _, p := range peers {
pID := ConvertPeerID(p)
pd := &peerDistance{
......@@ -48,7 +53,7 @@ func SortClosestPeers(peers []peer.ID, target ID) []peer.ID {
psarr = append(psarr, pd)
}
sort.Sort(psarr)
var out []peer.ID
out := make([]peer.ID, 0, len(psarr))
for _, p := range psarr {
out = append(out, p.p)
}
......
......@@ -165,7 +165,7 @@ func (rt *RoutingTable) NearestPeers(id ID, count int) []peer.ID {
}
bucket = rt.Buckets[cpl]
var peerArr peerSorterArr
peerArr := make(peerSorterArr, 0, count)
peerArr = copyPeersFromList(id, peerArr, bucket.list)
if len(peerArr) < count {
// In the case of an unusual split, one bucket may be short or empty.
......@@ -185,9 +185,13 @@ func (rt *RoutingTable) NearestPeers(id ID, count int) []peer.ID {
// Sort by distance to local peer
sort.Sort(peerArr)
var out []peer.ID
for i := 0; i < count && i < peerArr.Len(); i++ {
out = append(out, peerArr[i].p)
if count < len(peerArr) {
peerArr = peerArr[:count]
}
out := make([]peer.ID, 0, len(peerArr))
for _, p := range peerArr {
out = append(out, p.p)
}
return out
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment