Files
UnrealLuaDemo/Script/ts/src/Tests/Gameplay/ObjectPool.ts
T

78 lines
2.0 KiB
TypeScript
Raw Normal View History

/**
* 通用对象池(Object Pool),减少高频创建/销毁(子弹、特效、伤害飘字等)的 GC 压力。
*/
export interface IObjectPoolOptions<T> {
factory: (this: void) => T;
onAcquire?: (this: void, obj: T) => void;
onRelease?: (this: void, obj: T) => void;
maxCapacity?: number;
}
export class ObjectPool<T> {
private factory: (this: void) => T;
private onAcquire?: (this: void, obj: T) => void;
private onRelease?: (this: void, obj: T) => void;
private maxCapacity: number;
private idle: T[] = [];
private activeCount = 0;
private totalCreated = 0;
constructor(options: IObjectPoolOptions<T>) {
this.factory = options.factory;
this.onAcquire = options.onAcquire;
this.onRelease = options.onRelease;
this.maxCapacity = options.maxCapacity ?? 64;
}
Prewarm(count: number): void {
const target = math.min(count, this.maxCapacity);
while (this.idle.length < target) {
this.totalCreated++;
this.idle[this.idle.length] = this.factory();
}
}
Acquire(): T {
let obj: T;
if (this.idle.length > 0) {
obj = table.remove(this.idle) as T;
} else {
this.totalCreated++;
obj = this.factory();
}
this.activeCount++;
if (this.onAcquire) {
this.onAcquire(obj);
}
return obj;
}
Release(obj: T): void {
if (this.activeCount > 0) {
this.activeCount--;
}
if (this.onRelease) {
this.onRelease(obj);
}
if (this.idle.length < this.maxCapacity) {
this.idle[this.idle.length] = obj;
}
}
Clear(): void {
this.idle = [];
this.activeCount = 0;
}
GetIdleCount(): number {
return this.idle.length;
}
GetActiveCount(): number {
return this.activeCount;
}
GetTotalCreated(): number {
return this.totalCreated;
}
}