2022-09-30 06:34:14 +02:00
|
|
|
package bytesutil
|
2022-08-26 23:12:39 +02:00
|
|
|
|
|
|
|
import (
|
2022-12-12 23:31:16 +01:00
|
|
|
"strings"
|
2022-08-26 23:12:39 +02:00
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
2022-12-12 23:31:16 +01:00
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/fasttime"
|
2022-08-26 23:12:39 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// InternString returns interned s.
|
|
|
|
//
|
|
|
|
// This may be needed for reducing the amounts of allocated memory.
|
|
|
|
func InternString(s string) string {
|
2022-12-12 23:31:16 +01:00
|
|
|
ct := fasttime.UnixTimestamp()
|
|
|
|
if v, ok := internStringsMap.Load(s); ok {
|
|
|
|
e := v.(*ismEntry)
|
|
|
|
if atomic.LoadUint64(&e.lastAccessTime)+10 < ct {
|
|
|
|
// Reduce the frequency of e.lastAccessTime update to once per 10 seconds
|
|
|
|
// in order to improve the fast path speed on systems with many CPU cores.
|
|
|
|
atomic.StoreUint64(&e.lastAccessTime, ct)
|
|
|
|
}
|
|
|
|
return e.s
|
2022-08-26 23:12:39 +02:00
|
|
|
}
|
|
|
|
// Make a new copy for s in order to remove references from possible bigger string s refers to.
|
2022-12-12 23:31:16 +01:00
|
|
|
sCopy := strings.Clone(s)
|
|
|
|
e := &ismEntry{
|
|
|
|
lastAccessTime: ct,
|
|
|
|
s: sCopy,
|
|
|
|
}
|
|
|
|
internStringsMap.Store(sCopy, e)
|
|
|
|
|
|
|
|
if atomic.LoadUint64(&internStringsMapLastCleanupTime)+61 < ct {
|
|
|
|
// Perform a global cleanup for internStringsMap by removing items, which weren't accessed
|
|
|
|
// during the last 5 minutes.
|
|
|
|
atomic.StoreUint64(&internStringsMapLastCleanupTime, ct)
|
|
|
|
m := &internStringsMap
|
|
|
|
m.Range(func(k, v interface{}) bool {
|
|
|
|
e := v.(*ismEntry)
|
|
|
|
if atomic.LoadUint64(&e.lastAccessTime)+5*60 < ct {
|
|
|
|
m.Delete(k)
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
})
|
2022-08-26 23:12:39 +02:00
|
|
|
}
|
2022-12-12 23:31:16 +01:00
|
|
|
|
2022-08-26 23:12:39 +02:00
|
|
|
return sCopy
|
|
|
|
}
|
|
|
|
|
2022-12-12 23:31:16 +01:00
|
|
|
type ismEntry struct {
|
|
|
|
lastAccessTime uint64
|
|
|
|
s string
|
|
|
|
}
|
|
|
|
|
2022-08-26 23:12:39 +02:00
|
|
|
var (
|
2022-12-12 23:31:16 +01:00
|
|
|
internStringsMap sync.Map
|
|
|
|
internStringsMapLastCleanupTime uint64
|
2022-08-26 23:12:39 +02:00
|
|
|
)
|