.mousemove和memory,我需要优化这个吗?

时间:2012-12-10 09:36:53

标签: javascript jquery

我在这里创建了一个简单的轻量级测试演示:http://jsfiddle.net/CGr9d/

当我使用Chrome开发工具记录内存使用情况时,我得到:http://cl.ly/LSDl,它基本上会上升到某一点,然后再次下降并重新开始直到它再次达到上一个高点。 / p>

这是正常/好吗? 有没有办法优化我的代码,以减少内存密集?

这是我的mousemove功能:

$('body').mousemove(function(e) {
  //2000 is half the image width/height, of course used for centering
  $('.light-circle').css({ backgroundPosition: (e.pageX-2000)+'px '+(e.pageY-2000)+'px' });
});

感谢。

1 个答案:

答案 0 :(得分:4)

如果与选择器.light-circle匹配的元素没有改变,你可以像这样进行优化:

var circles = $('.light-circle');
$('body').mousemove(function(e) {
  //2000 is half the image width/height, of course used for centering
  circles.css({ backgroundPosition: (e.pageX-2000)+'px '+(e.pageY-2000)+'px' });
});

这样你就不会在每次移动鼠标时重新查询DOM,分配新的jQuery对象等等。

但是在垃圾收集环境中看到内存增加然后减少然后再次增加是完全正常的。