Warehouse address: github.com/haiyoucuv/W…

Introduce the concept of object pooling

In the last section we completed the dynamic creation of obstacles

However, after running for a while, it is found that there are n obstacles in the DOM node tree, and a batch of cards are stuck

Not only do these off-screen obstacles take up a lot of memory, but they don’t actually need to be updated or rendered at all

Object pooling

Use the object pool, reclaim the object, save the object in the pool, when needed do not have to re-create, just get from the pool can be

When the object is removed from the display list, put it back into the pool

  • createObjectPoolclass
  • Use a static variable to hold the object
  • Implement static methodsputInterface, incomingnameTo distinguish the types of objects to be saved, so that different types of objects can be saved
  • Implement static methodsgetInterface, incomingnameTo get an object of the corresponding type
/** * A simple generic object pool */
class ObjectPool {

	static objs = {};

	static put(name, obj) {
		const pool = ObjectPool.objs[name] || (ObjectPool.objs[name] = []);

		pool.push(obj);
	}

	static get(name) {
		const pool = ObjectPool.objs[name] || (ObjectPool.objs[name] = []);

		if (pool.length <= 0) {
			return null;
		}

		returnpool.shift(); }}Copy the code

transformPieMgr

  • createPieIs obtained from the object pool first. If the object pool does not exist, the object pool is created
  • whenPieOnce off screen, it is removed from the managed list, removed from the child node, and put back into the object pool
class PieMgr extends GameObject {

	/ *... * /

	/** * Create Pie */
	createPie() {
		// Use the object pool. If the object pool cannot be obtained, the object pool is empty and you need to create a new one
		const pie = ObjectPool.get("pie") | |new Pie();
		this.addChild(pie);
		this.pieArr.push(pie);  // Add the list to unified management
		pie.top = Math.random() * -150; // Highly random
		pie.left = winSize.width;   // Appears from the left side of the screen
	}

	update() {
		super.update();

		// All pies are shifted to the left simultaneously
		const { speed, pieArr } = this;
		pieArr.forEach((pie) = > {
			pie.left -= speed;
			if (pie.left <= -pie.size.width) {  // If you remove the screen
				this.pieArr.splice(this.pieArr.indexOf(pie), 1);    // Remove from the managed list
				this.removeChild(pie);                              // Remove the child node
				ObjectPool.put("pie", pie);                         // Add to the object pool}}); }}Copy the code

Run the case, hang up for 10 minutes, no card at all, the display list is only two Pie at most

Not even a day off the phone. Awesome