go-twig/utility.go
semihalev f1add2d820 Implement efficient LRU eviction strategy for attribute cache
- Added tracking of last access time and access count to cache entries
- Implemented eviction policy to remove least recently/frequently used entries
- Cache now removes 10% of entries when the cache is full, prioritizing by usage
- Added benchmarks and tests to verify eviction strategy
- Fixed the previously ineffective eviction strategy
- Improved cache efficiency for applications with many diverse object types

🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
2025-03-11 14:20:47 +03:00

42 lines
1 KiB
Go

package twig
import (
"bytes"
"io"
"sync"
)
// byteBufferPool is used to reuse byte buffers during node rendering
var byteBufferPool = sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
// GetByteBuffer gets a bytes.Buffer from the pool
func GetByteBuffer() *bytes.Buffer {
buf := byteBufferPool.Get().(*bytes.Buffer)
buf.Reset() // Clear any previous content
return buf
}
// PutByteBuffer returns a bytes.Buffer to the pool
func PutByteBuffer(buf *bytes.Buffer) {
byteBufferPool.Put(buf)
}
// WriteString optimally writes a string to a writer
// This avoids allocating a new byte slice for each string written
func WriteString(w io.Writer, s string) (int, error) {
// Fast path for strings.Builder, bytes.Buffer and similar structs that have WriteString
if sw, ok := w.(io.StringWriter); ok {
return sw.WriteString(s)
}
// Fallback path - reuse buffer from pool to avoid allocation
buf := GetByteBuffer()
buf.WriteString(s)
n, err := w.Write(buf.Bytes())
PutByteBuffer(buf)
return n, err
}