mirror of
https://github.com/VictoriaMetrics/VictoriaMetrics.git
synced 2024-12-11 14:53:49 +00:00
c06e7a142c
Cache sanitized label names and return them next time. This reduces the number of allocations and speeds up the SanitizeLabelName() function for common case when the number of unique label names is smaller than 100k
35 lines
764 B
Go
35 lines
764 B
Go
package discoveryutils
|
|
|
|
import (
|
|
"sync"
|
|
"sync/atomic"
|
|
)
|
|
|
|
// InternString returns interned s.
|
|
//
|
|
// This may be needed for reducing the amounts of allocated memory.
|
|
func InternString(s string) string {
|
|
m := internStringsMap.Load().(*sync.Map)
|
|
if v, ok := m.Load(s); ok {
|
|
sp := v.(*string)
|
|
return *sp
|
|
}
|
|
// Make a new copy for s in order to remove references from possible bigger string s refers to.
|
|
sCopy := string(append([]byte{}, s...))
|
|
m.Store(sCopy, &sCopy)
|
|
n := atomic.AddUint64(&internStringsMapLen, 1)
|
|
if n > 100e3 {
|
|
atomic.StoreUint64(&internStringsMapLen, 0)
|
|
internStringsMap.Store(&sync.Map{})
|
|
}
|
|
return sCopy
|
|
}
|
|
|
|
var (
|
|
internStringsMap atomic.Value
|
|
internStringsMapLen uint64
|
|
)
|
|
|
|
func init() {
|
|
internStringsMap.Store(&sync.Map{})
|
|
}
|