Coding Bare-Metal Loops - J Query

Problem
You’re calling $.each(array,fn) or $(selector).each(fn) to iterate over thousands of items in your code, and you suspect that all those function calls may be adding to your load time:

Solution

Use a for loop instead of .each(). To iterate over an array, it’s hard to beat this loop:

But there is a catch: this loop works only if your array has no “false” elements, that is,elements whose value is undefined, null, false, 0, or "". Even with that restriction, this loop is useful in many common cases, such as iterating over a jQuery object. Just be sure to cache the object in a variable:

It’s also common to have JSON data that contains an array of objects as in our example from Recipe (Loading Tables Faster):

If you know that none of the objects making up the elements of the names array will ever be null, it’s safe to use the fast loop.
For a more general-purpose loop that works with any array, there is always the classic loop that you’ll see in many places:

But you can improve that loop in three ways:

  • Cache the array length.
  • Use ++i, which is faster than i++ in some browsers.
  • Combine the test and increment of the loop variable to remove one name lookup.

The result is as follows:

To iterate over an object (not an array), you can use a for..inloop:

Discussion
$(selector).each(fn) is the customary way to create a jQuery object and iterate over it, but it’s not the only way. The jQuery object is an “array-like” object with .length and[0], [1], ..., [length-1] properties. Therefore, you can use any of the looping techniques you would use with any other array. And because the jQuery object never contains “false” elements, you can use the fastest for loop listed at the beginning of the solution.
If you use the time() function from Recipe 5.2 or another profiler to measure loop performance, be sure to test your actual code, not a simplified test case that just runs the loop without the full loop body. The simplified test would miss one potential benefit of the for loop: fewer name lookups resulting from less function nesting. See Recipe 5.13 for the details.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics