Object Pool Pattern 對(duì)象池模式
Intent 意義
Improve performance and memory use by reusing objects from a fixed pool instead of allocating and freeing them individually.
使用固定的對(duì)象池重用對(duì)象蹄衷,取代單獨(dú)地分配和釋放對(duì)象绪爸,以此來(lái)達(dá)到提升性能和優(yōu)化內(nèi)存使用的目的跃巡。
The Pattern 模式描述
Define a pool class that maintains a collection of reusable objects. Each object supports an “in use” query to tell if it is currently “alive”. When the pool is initialized, it creates the entire collection of objects up front (usually in a single contiguous allocation) and initializes them all to the “not in use” state.
When you want a new object, ask the pool for one. It finds an available object, initializes it to “in use”, and returns it. When the object is no longer needed, it is set back to the “not in use” state. This way, objects can be freely created and destroyed without needing to allocate memory or other resources.
定義一個(gè)保持著可重用對(duì)象集合的對(duì)象池類(lèi)。其中的每個(gè)對(duì)象支持對(duì)其“使用(in use)”狀態(tài)的訪(fǎng)問(wèn),以確定這一對(duì)象目前是否“存活(alive)”工窍。在對(duì)象池初始化時(shí)龄恋,它預(yù)先創(chuàng)建整個(gè)對(duì)象集合(通常為一塊連續(xù)堆區(qū)域)庶香,并將它們都置為“未使用(not in use)”狀態(tài)四敞。
當(dāng)我們想要?jiǎng)?chuàng)建一個(gè)新對(duì)象時(shí)泛源,就向?qū)ο蟪卣?qǐng)求。它將搜索到一個(gè)可用的對(duì)象忿危,將其初始化為“使用中(in use)”狀態(tài)并返回給你。當(dāng)該對(duì)象不再被使用時(shí)没龙,它將被置回“未使用(not in use)”狀態(tài)铺厨。使用該方法,對(duì)象便可以在無(wú)需進(jìn)行內(nèi)存或其他資源分配的情況下進(jìn)行任意的創(chuàng)建和銷(xiāo)毀硬纤。
When to Use It 使用情形
This pattern is used widely in games for obvious things like game entities and visual effects, but it is also used for less visible data structures such as currently playing sounds. Use Object Pool when:
- You need to frequently create and destroy objects.
- Objects are similar in size.
- Allocating objects on the heap is slow or could lead to memory fragmentation.
- Each object encapsulates a resource such as a database or network connection that is expensive to acquire and could be reused.
此模式被廣泛地應(yīng)用于游戲中的可見(jiàn)物體解滓,如游戲?qū)嶓w對(duì)象、各種視覺(jué)特效筝家。但是它也可在非可見(jiàn)的數(shù)據(jù)結(jié)構(gòu)上使用洼裤,比如當(dāng)前播放的聲音。
滿(mǎn)足以下情況可以使用對(duì)象池:
- 需要頻繁創(chuàng)建和銷(xiāo)毀對(duì)象時(shí)溪王。
- 對(duì)象大小一致時(shí)腮鞍。
- 在堆上分配對(duì)象緩慢或者會(huì)導(dǎo)致內(nèi)存碎片時(shí)值骇。
- 每個(gè)對(duì)象都封裝了很昂貴且又可以重用的資源,如數(shù)據(jù)庫(kù)移国、網(wǎng)絡(luò)的連接吱瘩。