动态内存分配导致影响Javascript性能的问题-创新互联
内存分配对性能的影响是很大的,分配内存本身需要时间,垃圾回收器回收内存也需要时间,所以应该尽量避免在堆里分配内存。不过直到最近优化HoLa cantk时,我才深刻的体会到内存分配对性能的影响,其中有一个关于arguments的问题挺有意思,写在这里和大家分享一下。

我要做的事情是用webgl实现canvas的2d API(这个话题本身也是挺有意思的,有空我们再讨论),drawImage是一个重要的函数,游戏会频繁的调用它,所以它的性能至关重要。drawImage的参数个数是可变的,它有三种形式:
- drawImage(image, x, y)
- drawImage(image, x, y, width, height)
- drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
第一个版本大概是这样实现的:
function Context() {
}
Context.prototype.drawImage3 = function(image, x, y) {
this.drawImage9(image, 0, 0, image.width, image.height, x, y, image.width, image.height);
}
Context.prototype.drawImage5 = function(image, dx, dy, dw, dh) {
this.drawImage9(image, 0, 0, image.width, image.height, dx, dy, dw, dh);
}
Context.prototype.drawImage9 = function(image, sx, sy, sw, sh, dx, dy, dw, dh) {
//DO IT
}
Context.prototype.drawImage = function(image, a, b, c, d, e, f, g, h) {
var n = arguments.length;
if(n === 3) {
this.drawImage3(image, a, b);
}else if(n === 5) {
this.drawImage5(image, a, b, c, d);
}else if(n === 9) {
this.drawImage9(image, a, b, c, d, e, f, g, h);
}
} 网站题目:动态内存分配导致影响Javascript性能的问题-创新互联
文章链接:http://www.scyingshan.cn/article/dehspg.html


咨询
建站咨询
