我一直在阅读有关对象池如何减少游戏垃圾收集的文章,特别是对于不断创建和销毁关键事件的事件监听器。他们提到对象池如何减少内存问题,但代码中没有说明如何实际做到这一点。
如何在 JavaScript 或 Java 中为事件建立对象池?
最佳答案
对于一般的对象池,您基本上需要维护自己的可用对象列表。如果所有对象都是同一类型,它会很好地工作。如果说你有一个类 Thing,你可能有一个 ThingPool
import java.util.ArrayDeque;
import java.util.Deque;
public class ThingPool {
public static class Thing {
}
// start with a big stack of objects
Deque<Thing> stack = new ArrayDeque<Thing>(1000);
/**
* Gets a new instance. If one exists in the stack use that,
* otherwise create a new one.
* @return
*/
public Thing getThing() {
if(stack.isEmpty())
return new Thing();
return stack.pop();
}
/**
* Does not actually delete it, just stores it for later use
* @param thing
*/
public void deleteThing(Thing thing) {
stack.push(thing);
}
/**
* You may need to clear your pool at some point
* if you have a great many objects in it
*/
public void clear() {
stack.clear();
}
}
当我对不同已知大小的许多矩阵进行一些繁重的工作并且遇到堆碎片问题时,我在 C 中使用了这种技术。
我没有在 Java 中使用过它,Java 的内存管理比 C 好得多。
关于java - 如何在 Java 或 JavaScript 中为事件监听器创建对象池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22534294/