diff --git a/mongo/description/selector_test.go b/mongo/description/selector_test.go index e83a751b94..a3566783dd 100644 --- a/mongo/description/selector_test.go +++ b/mongo/description/selector_test.go @@ -364,6 +364,27 @@ func BenchmarkSelector_Sharded(b *testing.B) { } } +func Benchmark_SelectServer_SelectServer(b *testing.B) { + topology := Topology{Kind: ReplicaSet} // You can change the topology as needed + candidates := []Server{ + {Kind: Mongos}, + {Kind: RSPrimary}, + {Kind: Standalone}, + } + + selector := writeServerSelector{} // Assuming this is the receiver type + + b.ReportAllocs() + b.ResetTimer() + + for i := 0; i < b.N; i++ { + _, err := selector.SelectServer(topology, candidates) + if err != nil { + b.Fatalf("Error selecting server: %v", err) + } + } +} + func TestSelector_Single(t *testing.T) { t.Parallel() diff --git a/mongo/description/server_selector.go b/mongo/description/server_selector.go index aee1f050cb..176f0fb53a 100644 --- a/mongo/description/server_selector.go +++ b/mongo/description/server_selector.go @@ -182,7 +182,17 @@ func (writeServerSelector) SelectServer(t Topology, candidates []Server) ([]Serv case Single, LoadBalanced: return candidates, nil default: - result := []Server{} + // Determine the capacity of the results slice. + selected := 0 + for _, candidate := range candidates { + switch candidate.Kind { + case Mongos, RSPrimary, Standalone: + selected++ + } + } + + // Append candidates to the results slice. + result := make([]Server, 0, selected) for _, candidate := range candidates { switch candidate.Kind { case Mongos, RSPrimary, Standalone: