【Unity UISystem】ListPool
是什麼
ListPool是Unity的UISystem源碼中的List對象池,它是由上一篇博文中提到的對象池ObjectPool
擴展而來的。具體源碼如下
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEngine.UI
{
internal static class ListPool<T>
{
// Object pool to avoid allocations.
private static readonly ObjectPool<List<T>> s_ListPool = new ObjectPool<List<T>>(null, Clear);
static void Clear(List<T> l) { l.Clear(); }
public static List<T> Get()
{
return s_ListPool.Get();
}
public static void Release(List<T> toRelease)
{
s_ListPool.Release(toRelease);
}
}
}
爲什麼
List是在遊戲中經常會用到的數據結構,比如需要讀取表格數據載入關卡表中的各項關卡,還有平時需要用到List的時候都需要臨時new一個,後面的銷燬完全交給C#,這種方式會導致不必要的GC,遊戲中能夠循環利用的數據結構都應該使用ListPool去管理。
怎麼做
創建時調用
List<Vector3> m_Positions = ListPool<Vector3>.Get();
銷燬時調用
ListPool<Vector3>.Release(m_Positions);
需要注意的是,創建和銷燬一定要成對出現,不然就失去了循環利用的效果了。
ObjectPool使用了一個Stack堆(last-in-first-out (LIFO))後進先出的結構,當我們需要新建(Get)一個新的Object的時候先從Stack的堆頂取出第一個,當使用結束的時候將其釋放掉(Release),也就是將其重新放回Stack堆裏面。原理其實很簡單,當然裏面增加了放進和放出時候的Action,可以用來傳入回調函數,分別在取出和釋放的時候調用。