internal/atlas: Better algorithm to release the temporary pixels

This commit is contained in:
Hajime Hoshi 2021-06-26 23:29:45 +09:00
parent 067e3c004d
commit 699bb095c3

View File

@ -39,50 +39,48 @@ var (
) )
type temporaryPixels struct { type temporaryPixels struct {
pixels []byte pixels []byte
pos int pos int
totalUse int notFullyUsedTime int
unusedTime int
} }
var theTemporaryPixels temporaryPixels var theTemporaryPixels temporaryPixels
func temporaryPixelsByteSize(size int) int {
l := 16
for l < size {
l *= 2
}
return l
}
func (t *temporaryPixels) alloc(size int) []byte { func (t *temporaryPixels) alloc(size int) []byte {
if len(t.pixels) < t.pos+size { if len(t.pixels) < t.pos+size {
newL := len(t.pixels) t.pixels = make([]byte, temporaryPixelsByteSize(t.pos+size))
if newL == 0 {
newL = 16
}
for newL < t.pos+size {
newL *= 2
}
t.pixels = make([]byte, newL)
t.pos = 0 t.pos = 0
} }
pix := t.pixels[t.pos : t.pos+size] pix := t.pixels[t.pos : t.pos+size]
t.pos += size t.pos += size
t.totalUse += size
return pix return pix
} }
func (t *temporaryPixels) resetAtFrameEnd() { func (t *temporaryPixels) resetAtFrameEnd() {
const maxUnusedTime = 60 const maxNotFullyUsedTime = 60
if t.totalUse == 0 { if temporaryPixelsByteSize(t.pos) < len(t.pixels) {
if t.unusedTime < maxUnusedTime { if t.notFullyUsedTime < maxNotFullyUsedTime {
t.unusedTime++ t.notFullyUsedTime++
} }
} else { } else {
t.unusedTime = 0 t.notFullyUsedTime = 0
} }
// Let the pixels GCed if this is not used for a while. // Let the pixels GCed if this is not used for a while.
if t.unusedTime == maxUnusedTime && len(t.pixels) > 0 { if t.notFullyUsedTime == maxNotFullyUsedTime && len(t.pixels) > 0 {
t.pixels = nil t.pixels = nil
} }
t.pos = 0 t.pos = 0
t.totalUse = 0
} }
func max(a, b int) int { func max(a, b int) int {