对象方法的setTimeout - ES5绑定还是闭包? [英] setTimeout on object method - ES5 bind, or closure?

查看:184
本文介绍了对象方法的setTimeout - ES5绑定还是闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在使用HTML5 Canvas做一些动画。如果我想要一个对象的方法动画,这将是更好的,性能明智(假设我不关心IE8):

Let's say I'm doing some animations with the HTML5 Canvas. If I'm looking to animate an object's method, which would be preferable, performance wise (assuming I don't care about IE8):

setTimeout(this.render.bind(this), 15);

var self = this;
setTimeout(function () { self.render() }, 15);

我的特殊情况不够强烈,无法在视觉上真正发挥作用;我只是想找出最好的做法。

My particular case isn't intense enough to really make a difference visually; I'm just trying to find out the best practice.

我认为用 bind 创建一个新函数比创建一个闭包更少开销,但我想问专家。

I would think creating a new function with bind would have less overhead than creating a closure, but I wanted to ask the experts.

推荐答案

JavaScript性能问题很棘手,因为那里的各种引擎都有非常不同的性能特征。一台发动机上的速度很快,而另一台发动机的速度很快。

JavaScript performance questions are tricky, because the various engines out there have very different performance characteristics. What's fast on one engine is slow on another.

你的闭合应该非常快;毕竟,所有函数都是闭包,而你的 self 变量是在包含立即数的上下文中定义的(所以没有很多内容可以查看它的范围链)。

Your closure should be very fast indeed; after all, all functions are closures and your self variable is defined in the immediately-containing context (so there isn't a lot of looking through the scope chain for it).

但从理论上讲,支持ES5功能的引擎本身可以优化 bind 的工作方式,使其更快(甚至不需要只有一个范围链查找。)

But in theory, an engine that supports ES5 features natively could optimize how bind works, making it even faster (no need for even just the one scope chain lookup).

这有关系吗?不,我会使用对你有意义的东西。请注意,IE8并不是唯一一个本身没有ES5功能的浏览器(尽管你总是可以使用其中一个es5垫片;与某些ES5功能不同, bind 可以通过ES3代码中的填充程序完美模拟—尽管要这样做,他们必须使用调用 / apply ,这可能比某些引擎上的闭包慢。)

Does it matter? No. I'd use what makes sense to you. Note that IE8 isn't the only browser out there that doesn't yet have ES5 features natively (although you can always use one of the es5 shims; unlike some ES5 features, bind can be perfectly emulated by shims in ES3 code — although to do it they have to use call/apply, which may be slower than a closure on some engines).

这篇关于对象方法的setTimeout - ES5绑定还是闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆