Question

I been reading articles about how object pooling reduces the garbage collection for games, especially for event listeners where the key event is constantly being created and destroyed. They mention how object pooling would decrease the memory problem but nowhere in code does it say how to actually do it.

How do you object pool for events in JavaScript or Java?

Was it helpful?

Solution

For object pooling in general you basically need to maintain your own list of available objects. It works nicely if all the objects are the same type. If say you have a class Thing you might have a 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();
    }
}

I used this technique in C when I was doing some heavy work with many matrices of a few different know sizes and was suffering from heap fragmentation problems.

I've not used it in Java which has much better memory management than C.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top