Chaining – Blessing or Curse?
The problem comes with the way in which the jQuery utilizes “chaining”. While this highly appreciated feature allows you to do a large set of things in the same line, thus allowing you do a lot of powerful things in a single line, the solution may not always be optimal. The ease of use of the jQuery chaining does not make this visible at first, and you may keep adding more steps to the code without thinking about the performance much.
However, the problem with computational code is that the time complexity of adding a new loop does not grow linearly, but the addition of each extra link makes the complexity grow exponentially, and thus, a simple addition of few steps may increase a lot of algorithmic complexity. This also causes the code to keep reiterating, thus causing a performance issue, which can have detrimental effects on the page load time.
Few Code Optimization Solutions
While there are many things that can be done to improve the overall performance of the code, the chaining slowdowns can be resolved or minimized by taking care of the following things in your code.
- Cache repeated selections – If you find that the code makes a condition-less call to some of the selectors, the value of that selector can be stored into a variable, thus ensuring that the actual selection only runs once, instead of being called once for each loop iteration.
- Merge chained functions – In normal coding, it makes sense to try to divide the result sets into small subsets so that each subroutine has to work on smaller dataset, however, for jQuery, it can result in calling another chained function. This sort of mindset needs to be developed, where you can put conditions to the inner chain-function to ignore the outer function’s element, thus calling a single function instead of multiple chain-functions.
- Use native DOM APIs – If they are available for the functionality you need, always try to make use of native DOM functions, since they will be faster than the jQuery, and if used in loops, the performance gain will be substantial.
- Other Algorithmic Changes – which can reduce loops or time complexity, will also help in improving the performance of the scripts.
Overall, most web developers do not consider performance as key for jQuery, since it is quite optimized and being a client-side application, it will not be loading the servers. Moreover, since load on client machines is lower the scripts will be expected to execute faster, however, putting small checks and optimizations will ensure that the code loads faster even for visitors, who have slow machines.