java - 如何在 Java 或 JavaScript 中为事件监听器创建对象池

标签 java javascript garbage-collection object-pooling

我一直在阅读有关对象池如何减少游戏垃圾收集的文章,特别是对于不断创建和销毁关键事件的事件监听器。他们提到对象池如何减少内存问题,但代码中没有说明如何实际做到这一点。

如何在 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/

相关文章:

java - 如何用 Map 的值键替换键值

java - 泛型和工厂模式

ruby-on-rails - Ruby 1.9 垃圾收集器,GC.disable/enable

javascript - [0] 在 $ ("#id")[0] 中做了什么?

java - 如何获取 Java 9 打印有关 GC 的 Java 8 样式信息

C# 循环引用对 GC 性能的影响

java - 错误: "the method add(Component) in the type Container is not applicable for the arguments (Square)

java - DrJava:无法使用 JDK8.0 运行代码

php - 如何制作一个不断更新的页面?

javascript - 禁用过渡动画