test: add comprehensive ts2lua-unreal TS/Lua 5.4 test suites and upgrade to v0.2.2
This commit is contained in:
1 parent
ee2e62bb34
commit
3dd61c32a9
75 files changed
+9929
-10
No files matched your search
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* 通用对象池(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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user