如何解决创建许多新对象会降低游戏速度吗?什么时候适合使用“对象池”?
我正在用Node和Javascript制作一个小型的在线游戏,并且在阅读了一些有关垃圾回收的知识之后,我不确定创建新对象是否被认为是不好的做法。我不仅在谈论使用“ new”关键字,而是在使用花括号定义具有多个属性的对象。
为了方便起见,我经常使用对象将信息传递给函数。这会减慢我的游戏速度吗?如果是这样,我应该担心更改方法还是对性能的权衡不是很大?
我已经了解了对象池和重用对象以避免创建新对象的方法,这是我应该实现的东西还是在大多数情况下认为GC足够好?
解决方法
对象是JS的常见部分,当然您可以根据需要使用它。只是不要忘记以下几点:
- 在不再需要
null
或undefined
时将其分配给对象属性,或将其删除:delete object[property];
- 重新分配对象的值,可以
- 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和对象引用it's pretty easy and informative的信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。