prometheus/utility/set.go
Julius Volz 4df5c7ab18 Optimize label matcher memory and runtime behavior.
This optimizes the runtime and memory allocation behavior for label matchers
other than type "Equal". Instead of creating a new set for every union of
fingerprints, this simply adds new fingerprints to the existing set to achieve
the same effect.

The current behavior made a production Prometheus unresponsive when running a
NotEqual match against the "instance" label (a label with high value
cardinality).

BEFORE:
BenchmarkGetFingerprintsForNotEqualMatcher        10   170430297 ns/op  39229944 B/op    40709 allocs/op

AFTER:
BenchmarkGetFingerprintsForNotEqualMatcher      5000      706260 ns/op    217717 B/op     1116 allocs/op

Change-Id: Ifd78e81e7dfbf5d7249e50ad1903a5d9c42c347a
2014-05-05 11:29:17 -04:00

59 lines
1.4 KiB
Go

// Copyright 2013 Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utility
// Set is a type which models a set.
type Set map[interface{}]struct{}
// Add adds an item to the set.
func (s Set) Add(v interface{}) {
s[v] = struct{}{}
}
// Remove removes an item from the set.
func (s Set) Remove(v interface{}) {
delete(s, v)
}
// Elements returns a slice containing all elements in the set.
func (s Set) Elements() []interface{} {
result := make([]interface{}, 0, len(s))
for k := range s {
result = append(result, k)
}
return result
}
// Has returns true if an element is contained in the set.
func (s Set) Has(v interface{}) bool {
_, p := s[v]
return p
}
// Intersection returns a new set with items that exist in both sets.
func (s Set) Intersection(o Set) Set {
result := Set{}
for k := range s {
if o.Has(k) {
result[k] = struct{}{}
}
}
return result
}