widgetPool - switch from map to slice

This commit is contained in:
Drew Weymouth
2023-07-08 14:02:15 -07:00
parent 673f86f792
commit 83b6d48560
+12 -12
View File
@@ -13,23 +13,26 @@ const (
WidgetTypeArtistPageHeader
WidgetTypePlaylistPageHeader
WidgetTypeTracklist
// keep at bottom
numWidgetTypes
)
// A pool to share commonly-used widgets across pages to reduce
// creation of new widgets and memory allocations.
// It is not thread-safe, which is fine for its current use.
type WidgetPool struct {
cache map[WidgetType][]cachedWidget
pool [][]pooledWidget
}
type cachedWidget struct {
type pooledWidget struct {
widget fyne.CanvasObject
releasedAt int64 // unixMillis
}
func NewWidgetPool() WidgetPool {
return WidgetPool{
cache: make(map[WidgetType][]cachedWidget),
pool: make([][]pooledWidget, numWidgetTypes),
}
}
@@ -37,11 +40,11 @@ func NewWidgetPool() WidgetPool {
// Returns nil if there is no available widget.
func (w *WidgetPool) Obtain(typ WidgetType) fyne.CanvasObject {
var widget fyne.CanvasObject
if ws, ok := w.cache[typ]; ok && len(ws) > 0 {
i := len(ws) - 1
widget = ws[i].widget
ws[i].widget = nil
w.cache[typ] = ws[:i]
if l := len(w.pool[typ]); l > 0 {
i := l - 1
widget = w.pool[typ][i].widget
w.pool[typ][i].widget = nil
w.pool[typ] = w.pool[typ][:i]
}
return widget
}
@@ -50,10 +53,7 @@ func (w *WidgetPool) Obtain(typ WidgetType) fyne.CanvasObject {
// The widget must not be modified by the releaser after release,
// since it may be Obtained for a new use at any time.
func (w *WidgetPool) Release(typ WidgetType, wid fyne.CanvasObject) {
if _, ok := w.cache[typ]; !ok {
w.cache[typ] = make([]cachedWidget, 0)
}
w.cache[typ] = append(w.cache[typ], cachedWidget{
w.pool[typ] = append(w.pool[typ], pooledWidget{
widget: wid,
releasedAt: time.Now().UnixMilli(),
})