Skip to content

Commit 1fd1bc2

Browse files
GODRIVER-3108 Optimize writeServerSelector (mongodb#1509)
Co-authored-by: Preston Vasquez <[email protected]>
1 parent 134d007 commit 1fd1bc2

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

mongo/description/selector_test.go

+21
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,27 @@ func BenchmarkSelector_Sharded(b *testing.B) {
364364
}
365365
}
366366

367+
func Benchmark_SelectServer_SelectServer(b *testing.B) {
368+
topology := Topology{Kind: ReplicaSet} // You can change the topology as needed
369+
candidates := []Server{
370+
{Kind: Mongos},
371+
{Kind: RSPrimary},
372+
{Kind: Standalone},
373+
}
374+
375+
selector := writeServerSelector{} // Assuming this is the receiver type
376+
377+
b.ReportAllocs()
378+
b.ResetTimer()
379+
380+
for i := 0; i < b.N; i++ {
381+
_, err := selector.SelectServer(topology, candidates)
382+
if err != nil {
383+
b.Fatalf("Error selecting server: %v", err)
384+
}
385+
}
386+
}
387+
367388
func TestSelector_Single(t *testing.T) {
368389
t.Parallel()
369390

mongo/description/server_selector.go

+11-1
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,17 @@ func (writeServerSelector) SelectServer(t Topology, candidates []Server) ([]Serv
182182
case Single, LoadBalanced:
183183
return candidates, nil
184184
default:
185-
result := []Server{}
185+
// Determine the capacity of the results slice.
186+
selected := 0
187+
for _, candidate := range candidates {
188+
switch candidate.Kind {
189+
case Mongos, RSPrimary, Standalone:
190+
selected++
191+
}
192+
}
193+
194+
// Append candidates to the results slice.
195+
result := make([]Server, 0, selected)
186196
for _, candidate := range candidates {
187197
switch candidate.Kind {
188198
case Mongos, RSPrimary, Standalone:

0 commit comments

Comments
 (0)