为什么jQuery选择器的功能与本机DOM方法相比太慢了 [英] Why is jQuery selector function so slow compared to native DOM methods

查看:150
本文介绍了为什么jQuery选择器的功能与本机DOM方法相比太慢了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个话题一般已经有几次辩论了,但是我正在寻找一个更加技术性和详细的洞察力来了解真正发生的事情。

I know this topic has been debated in general several times already, but I am looking for a more technical and detailed insight to understand what is really going on.

我设计了一系列测试,以将jQuery最基本的选择器#id和.class的速度与各种本机DOM方法进行比较。

I devised a series of tests to compare speed of jQuery's most basic selectors '#id' and '.class' to various native DOM methods.

我希望的是找出原因,结果是什么。

What I wish is to find out exactly why the results are what they are.

以下是测试: http://jsperf.com/jqueryspeed

主要的注意事项是getElementById是最快的。
为了比较,我添加了jQuery('#id')和jQuery.fn.init('#id')作为测试,两者之间的区别是,第一个是建立一个全新的jQuery对象,而第二个只运行原型功能,因此更快。所以,这两者之间的区别是可以理解的。

The main thing noticeable, is that getElementById is clearely the fastest of all. To compare, I added both jQuery('#id') and jQuery.fn.init('#id') as tests, the difference between the two is that the first one does instanciate a whole new jQuery object, while the second one only runs the prototype function, and is thus faster. So, the difference between those two is understandable.

然而,我不明白的主要区别是getElementById的速度与jQuery的速度之间的巨大差距。 fn.init,它有一个简单的测试,以特定的方式处理一个简单的('#id)请求,回到对getElementById本身的调用。

The main difference that I do NOT understand however, is the huge gap between the speed of getElementById and the speed of jQuery.fn.init, which has a simple test to handle a simple ('#id') request in a specific way, falling back to a call to getElementById itself.

所以为什么例如在Chrome上,这种方法比原来的方法慢8倍,即使它基本上只是一个包装器?

So, why for example on Chrome, is this method about 8 times slower than the native one, even though it basicly is just a wrapper for it ?

它也是大约3比打包的getElementById $(document.getElementById('#id'))慢4倍... ...

It is also about 3-4 times slower than the wrapped getElementById $(document.getElementById('#id'))...

有什么想法吗?

推荐答案

这是JQuery在使用简单的 $('selector' )

This is the amount of code jquery goes through when we use a simple $('selector')

http://james.padolsey.com/jquery/#v=1.10.2&fn=init

正如你所看到的,有很多的验证完成,正则表达式匹配,跨浏览器技巧等。

As you can see,there are plenty of validation done,regex matches,cross browser tricks etc.

重要的是意识到jquery是一个基于javascript的库.Javascript执行直接在浏览器上.JQuery在浏览器执行之前处理相当多的JavaScript代码。

Its important to realise that jquery is a library built on javascript.Javascript executes directly on the browser.Where as jquery processes quite a lot of javascript code before being executed by the browser.

我个人更喜欢jquery.I我真的不在乎保存这些纳秒秒。jquery提供的简单程度本身就是惊人的和艺术作品。

I personally prefer jquery.I am really not bothered about saving those nano seconds.The level of simplicity that jquery provides is phenomenal and an artpiece in itself.

这篇关于为什么jQuery选择器的功能与本机DOM方法相比太慢了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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