创建许多新对象会减慢游戏速度吗?什么时候适合使用"对象池"



我正在Node和Javascript中制作一个小型在线游戏,在阅读了一些关于垃圾收集的内容后,我不确定创建新对象何时被认为是不好的做法。我不仅仅是在谈论使用";新的";关键字,但我的意思是使用大括号定义一个具有多个属性的对象。

我经常使用对象将信息传递给函数,因为这很方便。这会让我的比赛慢下来吗?如果是,我是应该担心改变我的方法,还是性能权衡不是很大?

我读过关于对象池和重用对象以避免创建新对象的方法,这是我应该实现的吗,还是GC在大多数情况下足够好?

对象是JS的常见部分,当然您可以根据需要使用它。只是不要忘记几件事:

  1. 当不再需要对象属性时,将nullundefined指定给对象属性,或者删除它们:delete object[property];
  2. 重新分配对象的值,可以
  3. GC会收集所有没有引用的东西,所以如果你在某个地方仍然引用你的对象属性,它们就会保存在内存中
var x = { 
a: {
b: 2
}
}; 
// 2 objects are created. One is referenced by the other as one of its properties.
// The other is referenced by virtue of being assigned to the 'x' variable.
// Obviously, none can be garbage-collected.

var y = x;      // The 'y' variable is the second thing that has a reference to the object.
x = 1;          // Now, the object that was originally in 'x' has a unique reference
//   embodied by the 'y' variable.
var z = y.a;    // Reference to 'a' property of the object.
//   This object now has 2 references: one as a property, 
//   the other as the 'z' variable.
y = 'mozilla';  // The object that was originally in 'x' has now zero
//   references to it. It can be garbage-collected.
//   However its 'a' property is still referenced by 
//   the 'z' variable, so it cannot be freed.
z = null;       // The 'a' property of the object originally in x 
//   has zero references to it. It can be garbage collected.

一般来说,您可以阅读有关GC和对象引用的内容,它非常简单且内容丰富。

相关内容

最新更新