如果我在做多个动画,添加多个requestAnimationFrame回调在性能上是否正常?F.ex:
function anim1() {
// animate element 1
}
function anim2() {
// animate element 2
}
function anim3() {
// animate element 3
}
requestAnimationFrame(anim1);
requestAnimationFrame(anim2);
requestAnimationFrame(anim3);或者它被证明比使用单个回调更糟糕:
(function anim() {
requestAnimationFrame(anim);
anim1();
anim2();
anim3();
}());我之所以问,是因为我真的不知道幕后发生了什么,当你多次调用requestAnimationFrame时,它是否会对回调进行排队?
发布于 2020-04-22 22:22:23
我认为这些答案中的任何一个都不能真正解释我正在寻找的东西:“是否对requestAnimationFrame的n个调用”被取消(即每帧出队1个),或者在下一个帧中被调用。
当由requestAnimationFrame()排队的回调开始在单个帧中触发多个回调时出现
(mdn)
这暗示了后者,可以在同一帧中调用多个回调。
我通过以下测试确认了这一点。60 hz的刷新率转换为17ms的周期。如果是前者,两个时间戳之间的间隔不会在17毫秒以内,但事实并非如此。
let sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
let update = async timestamp => {
console.log('update called', timestamp)
await sleep(10);
requestAnimationFrame(update);
}
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
requestAnimationFrame(update);
发布于 2013-06-14 16:10:17
您应该只使用一个requestAnimationFrame调用作为对requestAnimationFrame的调用进行堆栈。因此,单个回调版本的性能更好。
发布于 2019-03-25 01:03:35
有人对此进行了基准测试。让我们谈谈..。
https://jsperf.com/single-raf-draw-calls-vs-multiple-raf-draw-calls
我看了性能比较(你也应该看一下)。欢迎你持不同意见。这些是画布元素上的绘制基元。
function timeStamp() {
return window.performance && window.performance.now ? window.performance.now() : new Date().getTime();
}
function frame() {
drawCircle();
drawLines();
drawRect();
}
function render() {
if (timeStamp() >= (time || timeStamp())) {
time = timeStamp() + delayDraw;
frame();
}
requestAnimationFrame(render);
}
function render1() {
if (timeStamp() >= (time || timeStamp())) {
time = timeStamp() + delayDraw;
drawCircle();
}
requestAnimationFrame(render1);
}
function render2() {
if (timeStamp() >= (time || timeStamp())) {
time = timeStamp() + delayDraw;
drawRect();
}
requestAnimationFrame(render2);
}
function render3() {
if (timeStamp() >= (time || timeStamp())) {
time = timeStamp() + delayDraw;
drawLines();
}
requestAnimationFrame(render3);
}我认为这段代码对7次timestamp()调用和2次timestamp()调用进行了基准测试。看看Chrome46和Chrome47之间的区别。
我认为这是优化得很好的,所以不会有什么不同。这只是在这一点上测量噪声。
我的结论是,这不需要针对我的应用程序进行手动优化。
如果你担心性能,看看Chrome59(1.8Mops/sec)和Chrome71(506kops/sec)之间的区别。
https://stackoverflow.com/questions/17103785
复制相似问题