首页 > javascript对象池是什么鬼来的?求指指点点

javascript对象池是什么鬼来的?求指指点点

javascript/*
 * The object to be held within the Object Pool.
 */
function Obj() {
  this.inUse = false; // Is true if the object is currently in use
  /*
   * Sets an object not in use to default values
   */
  this.init = function(/*values*/) {
    /*code to initialize object to default values*/
  };
  /*
   * Spawn an object into use
   */
  this.spawn = function(/*values if any*/) {
    /*code to set values if any*/
    this.inUse = true;
  }
  /*
   * Use the object. Return true if the object is ready to be
   * cleared (such as a bullet going of the screen or hitting
   * an enemy), otherwise return false.
   */
  this.use = function() {
    if (/*object is ready to be reused*/) {
      return true;
    } else {
      /*code to use object*/
      return false;
    }
  };
  /*
   * Resets the object values to default
   */
  this.clear = function() {
    /*code to reset values*/
    this.inUse = false;
  };
}
/**
 * The Object Pool. Unused objects are grabbed from the back of
 * the array and pushed to the front of the array. When using an
 * object, if the object is ready to be removed, it splices the
 * array and pushes the object to the back to be reused.
 */
function Pool() {
  var size = 20; // Max objects allowed in the pool
  var pool = [];
  /*
   * Populates the pool array with objects
   */
  this.init = function() {
    for (var i = 0; i < size; i++) {
      // Initialize the objects
      var obj = new Obj();
      obj.init(/*values*/);
      pool[i] = obj;
    }
  };
  /*
   * Grabs the last item in the list and initializes it and
   * pushes it to the front of the array.
   */
  this.get = function(/*values*/) {
    // If the last item in the array is in use, the pool is full
    if(!pool[size - 1].inUse) {
      pool[size - 1].spawn(/*values if any*/);
      pool.unshift(pool.pop());
    }
  };
  /*
   * Uses any alive objects in the pool. If the call returns true,
   * the object is ready to be cleared and reused.
   */
  this.use = function() {
    for (var i = 0; i < size; i++) {
      // Only use objects that are currently in use
      if (pool[i].inUse) {
        if (pool[i].use()) {
          pool[i].clear();
          pool.push((pool.splice(i,1))[0]);
        }
      } else {
        // The first occurrence of an unused item we can
        // break looping over the objects.
        break;
      }
    }
  };
}

想看更多,请看原文链接:
http://blog.sklambert.com/javascript-object-pool/

对象池,怎么用呢?求解答?是不是可以进行性能优化呢?


1.对象池是什么

关于这个楼上说的很清楚。不再重复。

2.应用场景

那种画面有列表的情况。比如新闻列表,所有的新闻可以当成一个对象池,每条新闻就是其中的每个object.
新闻的CRUD对应的就是object的各种方法。
这种在前端MVC中有类似于collection的概念。

3.好处

代码组织的比较好,逻辑清晰,易于维护。如果说关于性能优化啥的,我觉得吧别啥明显的优势,当然这也要看跟啥比吧。
总之,还是比较推荐这种编程风格。


对象池还第一次听说,按照博主给出的例子,不难看出对象池就是用来性能优化的
用法代码还是挺清楚的,从对象池中取可用对象(use)、取最后一个对象(get)。。

【热门文章】
【热门文章】