diff --git a/pkg/collector/distinct_string_collector.go b/pkg/collector/distinct_string_collector.go index 2b8fc7e38b80..ca881703e269 100644 --- a/pkg/collector/distinct_string_collector.go +++ b/pkg/collector/distinct_string_collector.go @@ -106,13 +106,14 @@ func (d *DistinctString) Size() int { // Diff returns all new strings collected since the last time diff was called func (d *DistinctString) Diff() ([]string, error) { - d.mtx.Lock() - defer d.mtx.Unlock() - + // can check diffEnabled without lock because it is not modified after creation if !d.diffEnabled { return nil, errDiffNotEnabled } + d.mtx.Lock() + defer d.mtx.Unlock() + ss := make([]string, 0, len(d.new)) for k := range d.new { diff --git a/pkg/collector/distinct_value_collector.go b/pkg/collector/distinct_value_collector.go index 3e800cc5e3ed..a83596676397 100644 --- a/pkg/collector/distinct_value_collector.go +++ b/pkg/collector/distinct_value_collector.go @@ -111,13 +111,14 @@ func (d *DistinctValue[T]) Size() int { // Diff returns all new strings collected since the last time diff was called // returns nil if diff is not enabled func (d *DistinctValue[T]) Diff() ([]T, error) { - d.mtx.Lock() - defer d.mtx.Unlock() - + // can check diffEnabled without lock because it is not modified after creation if !d.diffEnabled { return nil, errDiffNotEnabled } + d.mtx.Lock() + defer d.mtx.Unlock() + ss := make([]T, 0, len(d.new)) for k := range d.new { ss = append(ss, k) diff --git a/pkg/collector/scoped_distinct_string.go b/pkg/collector/scoped_distinct_string.go index 3385591977dc..abe902122c72 100644 --- a/pkg/collector/scoped_distinct_string.go +++ b/pkg/collector/scoped_distinct_string.go @@ -89,13 +89,13 @@ func (d *ScopedDistinctString) Exceeded() bool { // Diff returns all new strings collected since the last time Diff was called func (d *ScopedDistinctString) Diff() (map[string][]string, error) { - d.mtx.Lock() - defer d.mtx.Unlock() - if !d.diffEnabled { return nil, errDiffNotEnabled } + d.mtx.Lock() + defer d.mtx.Unlock() + ss := map[string][]string{} for k, v := range d.cols {