8

在以疯狂的速度创建多个 DIV 时,我试图找出有关性能的最佳实践。例如,在每个 .mousemove 事件中...

$('head').append("<style>.draw {width: 20px; height: 20px; position:fixed;</style>");

$(document).mousemove(function(mouseMOVE) {
//current mouse position
    var mouseXcurrent = mouseMOVE.pageX;
    var mouseYcurrent = mouseMOVE.pageY;

//function to create div
   function mouseTRAIL(mouseX, mouseY, COLOR) {
        $('body').append("<div class='draw' style='top:" + mouseY + "px; left:" + mouseX + "px; background: " + COLOR + ";'></div>");
    }

// function call to create <div> at current mouse positiion
   mouseTRAIL(mouseXcurrent, mouseYcurrent, '#00F');

// Remove <div>
    setTimeout(function() {
        $('.draw:first-child').remove();
    }, 250);
});

所以,这一切都很好而且很花哨,但它的效率非常低(特别是当我尝试填充每个鼠标移动位置之间的空间时)。这是一个例子......

$('head').append("<style>.draw {width: 20px; height: 20px; position:fixed;</style>");

$(document).mousemove(function(mouseMOVE) {
//current mouse position
    var mouseXcurrent = mouseMOVE.pageX;
    var mouseYcurrent = mouseMOVE.pageY;

// function to create div
    function mouseTRAIL(mouseX, mouseY, COLOR) {
        $('body').append("<div class='draw' style='top:" + mouseY + "px; left:" + mouseX + "px; background: " + COLOR + ";'></div>");
    }

// function call to create <div> at current mouse positiion
    mouseTRAIL(mouseXcurrent, mouseYcurrent, '#00F');

// variabls to calculate position between current and last mouse position
    var num = ($('.draw').length) - 3;
    var mouseXold = parseInt($('.draw:eq(' + num + ')').css('left'), 10);
    var mouseYold = parseInt($('.draw:eq(' + num + ')').css('top'), 10);
    var mouseXfill = (mouseXcurrent + mouseXold) / 2;
    var mouseYfill = (mouseYcurrent + mouseYold) / 2;

// if first and last mouse postion exist, function call to create a div between them
    if ($('.draw').length > 2) {
    mouseTRAIL(mouseXfill, mouseYfill, '#F80');
    }

// Remove <div>
    setTimeout(function() {
        $('.draw:first-child').remove();
        $('.draw:nth-child(2)').remove();
    }, 250);
});


我真的不知道如何改进。相信我,我已经尝试过研究,但效果不佳……我正在寻找一些建议、示例或指向更好实践的链接……

请注意,我正在自学编码。我是一名平面设计专业的学生,​​这就是我在课外度过暑假的方式......制作一些小项目来自学 JavasSript,有趣的东西 :)


我已经设置了一些 jsfiddles 来展示我在做什么......

鼠标轨迹,更多元素- 非常非常慢
鼠标轨迹,更少元素- 非常慢
鼠标轨迹,Bare Bones - 慢

4

2 回答 2

3

这里有多种不良做法:

  • 使用元素而不是画布
  • 通过 jQuery 使用这些元素
  • 滥用 jQuery,就好像你故意让它变慢一样
  • 将以上所有内容填充到 mousemove 处理程序中

这里的根本问题实际上是使用元素而不是画布。修复后,与 DOM 的交互应该变得最小,因此也修复了其他点。

此外,那些声称这工作正常的人并没有检查他们的 CPU 使用率。在我的 Core I5-2500K 上,一个内核立即被最大化,这对于像在屏幕上渲染鼠标轨迹这样的琐碎事情来说是荒谬和不可接受的。我可以很好地想象这在旧计算机上非常非常慢。所以是的,它很顺利,但代价是使用的资源量足以让 10-20 多个标签正确地执行相同的操作。

当快速移动鼠标时,这需要 7-14% 的 cpu,需要 25%。

于 2012-05-19T13:02:39.593 回答
1

你应该小心不要导致回流,只坚持重绘。->回流在 DOM 环境中何时发生?

所以创建<div>s 是没有选择的。- 但你不需要:)

只需创建尽可能多<div>的 s,然后重新定位它们。如果将它们放在数组中,则只需要一个指向当前最大整数的整数,并且在每次鼠标移动时,您都会增加该值(一旦达到数组长度,将其设置为 0)并重新定位<div>指向的那个由那个数字。

于 2012-05-19T12:49:03.550 回答