我想制作一个extendDeep()函数,该函数不会为GC造成任何垃圾。
垃圾收集器需要尽可能不活动。
参考:https://www.scirra.com/blog/76/how-to-write-low-garbage-real-time-javascript
这是我要修改的extendDeep()函数:
function extendDeep(parent, child) {
var i, toStr = Object.prototype.toString,
astr = "[object Array]";
child = child || {};
for (i in parent) {
if (parent.hasOwnProperty(i)) {
if (typeof parent[i] === 'object') {
child[i] = (toStr.call(parent[i]) === astr) ? [] : {};
extendDeep(parent[i], child[i]);
} else {
child[i] = parent[i];
}
}
}
return child;
}
该函数不必返回任何东西。因为重新调谐的对象是产生垃圾的原因。
假定父对象的所有属性都可以通过引用获得(对象的重用)
最佳答案
这实际上是一个比我最初想到的有趣的问题。阅读建议的链接后,很明显,文章作者提倡对象池。所以像
function Pool(fConstructor, nMaxSize, fCleanFunction) {
this.aObjectPool = [];
this.nMaxSize = nMaxSize;
this.fCleanFunction = fCleanFunction;
this.fConstructor = fConstructor;
}
Pool.prototype.get = function() {
return this.aObjectPool.pop() || new this.fConstructor();
}
Pool.prototype.recycle = function(oObject) {
if (aObjectPool.length < this.nMaxSize) {
fCleanFunction(oObject);
this.aObjectPool.push(oObject);
}
}
function wipeArray(aArray) {
aArray.length = 0;
}
function wipeObject(oObject) {
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
delete obj[p];
}
}
};
var oArrayPool = new Pool(Array, 50, wipeArray);
var oObjectPool = new Pool(Object, 50, wipeObject);
可用于实现池。然后,您可以使用pool.get()替换扩展深度函数中的[]和{}。
当然,要实现此目的,您还需要确保您正在回收旧的对象和数组,而不仅仅是将它们用于垃圾回收。