From 9c01947b1c83a796f94708835b64dfeffc13e70d Mon Sep 17 00:00:00 2001 From: Arceliar Date: Thu, 16 May 2019 18:10:47 -0500 Subject: [PATCH] reduce allocations in switch --- src/yggdrasil/switch.go | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/yggdrasil/switch.go b/src/yggdrasil/switch.go index 0e164b9..1bc4050 100644 --- a/src/yggdrasil/switch.go +++ b/src/yggdrasil/switch.go @@ -577,23 +577,28 @@ func (t *switchTable) start() error { return nil } +type closerInfo struct { + port switchPort + dist int +} + // Return a map of ports onto distance, keeping only ports closer to the destination than this node // If the map is empty (or nil), then no peer is closer -func (t *switchTable) getCloser(dest []byte) map[switchPort]int { +func (t *switchTable) getCloser(dest []byte) []closerInfo { table := t.getTable() myDist := table.self.dist(dest) if myDist == 0 { // Skip the iteration step if it's impossible to be closer return nil } - closer := make(map[switchPort]int, len(table.elems)) + t.queues.closer = t.queues.closer[:0] for _, info := range table.elems { dist := info.locator.dist(dest) if dist < myDist { - closer[info.port] = dist + t.queues.closer = append(t.queues.closer, closerInfo{info.port, dist}) } } - return closer + return t.queues.closer } // Returns true if the peer is closer to the destination than ourself @@ -656,9 +661,9 @@ func (t *switchTable) handleIn(packet []byte, idle map[switchPort]time.Time) boo var bestDist int var bestTime time.Time ports := t.core.peers.getPorts() - for port, dist := range closer { - to := ports[port] - thisTime, isIdle := idle[port] + for _, cinfo := range closer { + to := ports[cinfo.port] + thisTime, isIdle := idle[cinfo.port] var update bool switch { case to == nil: @@ -667,9 +672,9 @@ func (t *switchTable) handleIn(packet []byte, idle map[switchPort]time.Time) boo //nothing case best == nil: update = true - case dist < bestDist: + case cinfo.dist < bestDist: update = true - case dist > bestDist: + case cinfo.dist > bestDist: //nothing case thisTime.Before(bestTime): update = true @@ -678,7 +683,7 @@ func (t *switchTable) handleIn(packet []byte, idle map[switchPort]time.Time) boo } if update { best = to - bestDist = dist + bestDist = cinfo.dist bestTime = thisTime } } @@ -711,6 +716,7 @@ type switch_buffers struct { size uint64 // Total size of all buffers, in bytes maxbufs int maxsize uint64 + closer []closerInfo // Scratch space } func (b *switch_buffers) cleanup(t *switchTable) {