jQuery size() vs length




I have seen a lot of jQuery developers getting confused over the usage of the jQuery size() function and length property. Both of these return the count of elements on the page or jQuery object.

jQuery documentation however says that the length property should be preferred over the size() function as using the length property will avoid an extra method call. So it is quicker.

There’s a performance test created over here by Charles which counts the number of unordered list (<li>) on the page to demonstrate the same.

$(‘li’).size();
$(‘li’).length; // quicker

Running the sample above shows a slight performance advantage of using length over size()jquery size vs length

Note: Some times the size() returns a faster result (on IE 8). In my opinion, keeping both the size() and length property in the API is confusing. I have been using size() as it is an abstraction over the length property. Although, the length makes more sense since it is the recommended approach and is familiar especially to those who are JavaScript developers.

Will you give this article a +1 ? Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "jQuery size() vs length"
  1. lustos said...
    July 1, 2011 at 7:48 AM

    Good one. Did you also know that if you use jquery instead of the ajax toolkit for collapsible panels is faster too?

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions