setTimeout()与字符串或(匿名)函数引用?速度 [英] setTimeout() with string or (anonymous) function reference? speedwise

查看:112
本文介绍了setTimeout()与字符串或(匿名)函数引用?速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法中哪一种更快,为什么?

Which one of these two ways is faster and why?

window.setTimeout("func()", 100);

window.setTimeout(function(){func();}, 100);

我想如果没有其他原因,除了John Resig和所有ninjas使用它,我猜,因为它已经解析,而不是第一种方式,它必须创建一个新的解析东西。我模糊地回忆起这是人们不喜欢eval()的原因之一。

I'm guessing the second way is faster if for no other reason other than John Resig and all the ninjas use it, I'm guessing because it already parsed as opposed to the first way which it would have to create a new parsing "thingie". I vaguely recall this being one of the reasons people don't like eval().

同时,我在这里,在第二个代码snipplet,

Also while I have you here, in the second code snipplet, is the first semi-colon considered good practice in such a case?

推荐答案

有第三个更快/更简单的选项:

There's a third faster/simpler option:

window.setTimeout(func, 100);

...与您的问题严格相关,第二个更快,因为它仍然是一个参考 - 不评估,这总是相当昂贵。至于分号,是的,它是一个很好的习惯,总是使用它们。他们应该永远不是可选的IMO,但很多会不同意我在那里...但你不能真正反对在代码中显式,这总是一个的东西。

...strictly relating to your question, the second is faster, as it's still a reference - not an evaluation, which is always fairly expensive. As for the semicolon, yes it's a good practice to always use them. They should never have been optional IMO, but plenty will disagree with me there...but you can't really argue against being explicit in your code, that's always a good thing.

这篇关于setTimeout()与字符串或(匿名)函数引用?速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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