From 003ad0deda9f849156b8086ec81dd50611ff755c Mon Sep 17 00:00:00 2001 From: Brendan Chou <3680392+BrendanChou@users.noreply.github.com> Date: Thu, 23 May 2024 13:59:54 -0400 Subject: [PATCH] improve performance of ContainsDuplicates --- protocol/lib/collections.go | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/protocol/lib/collections.go b/protocol/lib/collections.go index 52d8baf794..94ffc732e6 100644 --- a/protocol/lib/collections.go +++ b/protocol/lib/collections.go @@ -7,13 +7,16 @@ import ( // ContainsDuplicates returns true if the slice contains duplicates, false if not. func ContainsDuplicates[V comparable](values []V) bool { - seenValues := make(map[V]bool) - for _, val := range values { - if _, exists := seenValues[val]; exists { + // Store each value as a key in the mapping. + seenValues := make(map[V]struct{}, len(values)) + for i, val := range values { + // Add the value to the mapping. + seenValues[val] = struct{}{} + + // Return early if the size of the mapping did not grow. + if len(seenValues) <= i { return true } - - seenValues[val] = true } return false