jQuery 选择器和变量
写,性能上有什么明显的优势吗
var e = $("#el");
e.css(...);
e.attr(...);
....
e.click(...);
相比于
$("#el").css(...);
$("#el").attr(...);
....
$("#el").click(...);
?
Is there any obvious advantage in performance in writing
var e = $("#el");
e.css(...);
e.attr(...);
....
e.click(...);
instead of
$("#el").css(...);
$("#el").attr(...);
....
$("#el").click(...);
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,在第一个版本中,您不会每次都再次找到该元素,这总是需要一些成本。还有第三种选择,链接:
这是您将看到的更常见的方法,但每个开发人员的样式都不同......该库在设计时就考虑到了链接。在 ID 选择器的特定情况下,
document.getElementById()
的成本非常非常小,对于任何其他选择器,它的成本加起来要快得多。Yes, in the first version you're not finding the element again each time, which always has some cost. There's also a third option, chaining:
This is the more common approach you'll see, but the styles vary per developer...the library was designed with chaining in mind. In your specific case of an ID selector, the cost of
document.getElementById()
is very minimal, with any other selector it adds up much more quickly.是的。此外,你可以获得更好的可读性(特别是如果你用事物的本质来命名):
Yes. Moreover, you get better readability (especially if you name things with what they are):
如果明显的优势是指在这种情况下对用户来说显而易见的优势……那么可能不是,因为现在没有人抱怨。另一方面,如果您的意思是在代码的生命周期(以及必须维护代码的人的生命周期中[包括您自己])有明显的优势,那么第一个就具有相当大的优势。首先,运行速度更快,因为等效的非 jQuery 代码是:
(Windows XP 上的 Chrome 7.0.517.5 速度提高了 25%。请参阅我在 jsperf 上创建的这个测试 .com)
与 Second相比
,它更具可读性,正如 glebm 所指出的那样。如果您使用描述性变量名称 - 这将使以后更快地理解和编辑。
If by obvious advantages you mean obvious to the user in this instance ... then probably not, as no one is complaining right now. If on the other hand, if you mean obvious advantages over the lifecycle of your code (and in the life-span of those who must maintain it [yourself included]) then the first has quite an advantage. First, it's faster to run as the equivalent non-jQuery code is:
(25% faster with Chrome 7.0.517.5 on Windows XP. See this test I created on jsperf.com)
versus
Second, it's much more readable, as glebm has pointed out. If you use descriptive variable names -- which makes it faster to comprehend and edit later.
是的,第一个会有更好的性能,因为 jQuery 只需要解析选择器并创建一个节点集一次。当然,差异可能并不明显。
Yes, the first one will have better performance, since jQuery only has to parse the selector and create a node set once. Of course, the difference may not be noticeable.
就性能而言,还不足以说明问题。在可读性方面?优势非常明显
In performance, not enough to tell. In readability? Very obvious advantage