perf: make bootstrap saves O(N)
Jorropo committed
Sep 6, 2023 at 00:32 UTC
66590e350f6dbdf9da77e9548a91f9ce96d803dd
1 file changed
+18
-21
core/bootstrap/bootstrap.go
+18
-21
@@ -192,22 +192,24 @@ func saveConnectedPeersAsTemporaryBootstrap(ctx context.Context, host host.Host,
192
193
bootstrapPeers := cfg.BootstrapPeers()
194
backupPeers := make([]peer.AddrInfo, 0, cfg.MaxBackupBootstrapSize)
195
+ foundPeers := make(map[peer.ID]struct{}, cfg.MaxBackupBootstrapSize+len(bootstrapPeers))
196
+
197
+ // Don't record bootstrap peers
198
+ for _, b := range bootstrapPeers {
199
+ foundPeers[b.ID] = struct{}{}
200
+ }
201
202
// Choose peers to save and filter out the ones that are already bootstrap nodes.
203
for _, p := range connectedPeers {
198
- found := false
199
- for _, bootstrapPeer := range bootstrapPeers {
200
- if p == bootstrapPeer.ID {
201
- found = true
202
- break
203
- }
204
- }
205
- if !found {
206
- backupPeers = append(backupPeers, peer.AddrInfo{
207
- ID: p,
208
- Addrs: host.Network().Peerstore().Addrs(p),
209
- })
204
+ if _, found := foundPeers[p]; found {
205
+ continue
206
}
207
+ foundPeers[p] = struct{}{}
208
+
209
+ backupPeers = append(backupPeers, peer.AddrInfo{
210
+ ID: p,
211
+ Addrs: host.Network().Peerstore().Addrs(p),
212
+ })
213
214
if len(backupPeers) >= cfg.MaxBackupBootstrapSize {
215
break
@@ -222,17 +224,12 @@ func saveConnectedPeersAsTemporaryBootstrap(ctx context.Context, host host.Host,
224
225
// Add some of the old saved peers. Ensure we don't duplicate them.
226
for _, p := range oldSavedPeers {
225
- found := false
226
- for _, sp := range backupPeers {
227
- if p.ID == sp.ID {
228
- found = true
229
- break
230
- }
227
+ if _, found := foundPeers[p.ID]; found {
228
+ continue
229
}
230
+ foundPeers[p.ID] = struct{}{}
231
233
- if !found {
234
- backupPeers = append(backupPeers, p)
235
- }
232
+ backupPeers = append(backupPeers, p)
233
234
if len(backupPeers) >= cfg.MaxBackupBootstrapSize {
235
break