【发布时间】:2017-06-16 12:12:02
【问题描述】:
我正在构建一个 WebGL 游戏,我已经开始研究性能瓶颈。我可以看到当 GC 进行时 FPS 有很多小的下降。因此,我创建了一个小型内存池处理程序。开始使用后还是看到很多GC,我可能会怀疑自己有什么问题。
我的内存池代码如下所示:
function Memory(Class) {
this.Class = Class;
this.pool = [];
Memory.prototype.size = function() {
return this.pool.length;
};
Memory.prototype.allocate = function() {
if (this.pool.length === 0) {
var x = new this.Class();
if(typeof(x) == "object") {
x.size = 0;
x.push = function(v) { this[this.size++] = v; };
x.pop = function() { return this[--this.size]; };
}
return x;
} else {
return this.pool.pop();
}
};
Memory.prototype.free = function(object) {
if(typeof(object) == "object") {
object.size = 0;
}
this.pool.push(object);
};
Memory.prototype.gc = function() {
this.pool = [];
};
}
然后我像这样使用这个类:
game.mInt = new Memory(Number);
game.mArray = new Memory(Array); // this will have a new push() and size property.
// Allocate an number
var x = game.mInt.allocate();
<do something with it, for loop etc>
// Free variable and push into mInt pool to be reused.
game.mInt.free(x);
我对数组的内存处理基于使用 myArray.size 而不是 length,它会跟踪超维数组(已被重用)中的实际当前数组大小。
所以对于我的实际问题:
使用这种方法可以避免 GC 并在播放期间保留内存。我在函数内部使用“var”声明的变量是否仍然是 GC,即使它们从我的 Memory 函数作为 new Class() 返回?
例子:
var x = game.mInt.allocate();
for(x = 0; x < 100; x++) {
...
}
x = game.mInt.free(x);
由于幕后的一些内存复制,这是否仍会导致“var”的内存垃圾收集? (这会使我的内存处理程序无用)
对于我想要获得高 FPS 的游戏,我的方法是否良好/有意义?
【问题讨论】:
-
基元按值复制。 => 我不知道分配值是否有用..
-
我只会做 x=5;然后 x=undefined...
-
@jonasw 你的意思是例如:x = game.mInt.allocate();游戏.mint.free(x); x = 未定义;还是您的意思是简单地跳过我的内存处理? (x = undefined 会导致 GC 启动,对吗?)
-
我会跳过它。新号码(5);创建一个数字对象,与原语相比,它的内存消耗相当大。
标签: javascript memory-management garbage-collection