Difference between jQuery length and size()

The difference between jQuery length and size() is summarized as follows:
1.length is a property, size() is a method.

2. If you just want to get the number of elements, both have the same effect. The values ​​obtained by $("img").length and $("img").size() are the same.

3. If you calculate the length of a string or the number of elements of an array, you can only use length, such as $("#text").val().length.

 Take a look at their execution time, http://jsperf.com/size-vs-length uses this to detect

The difference between size() length in jquery

From the figure, we can see that the size() method is 38% slower than length. What is the reason?

Here's why:

The difference between size() length in jquery

Take a look at the explanation on the official website (http://api.jquery.com/size/):

The .size() method is deprecated as of jQuery 1.8. Use the property instead. .length

The .size()method is functionally equivalent to the .lengthproperty; however, the .lengthproperty is preferred because it does not have the overhead of a function call.
It can be seen from the above that size() is implemented by calling the length property

length replaces size() after jQuery 1.8, because length doesn't need to return a function call, which is better.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324917980&siteId=291194637