As mentioned earlier, Backbone itself will not usually be the source of CPU-related performance issues, because these issues tend to be caused by specific components rather than the overall site architecture. However, there is one way that Backbone can contribute to such problems, and that is by making it easy to repeat the same work in multiple places. For instance, let's imagine that you are creating a dashboard page that will use one main View
class to show your user various pieces of data, and a number of child Views
to render each of these pieces of data. In addition, let's imagine that each of these pieces of data will update periodically. Normally, you would tie the updating of that data to an AJAX response or a user event, but under certain circumstances, you might instead want to use a setInterval
statement. For instance, onScroll
events are known to be problematic, so many developers avoid them and instead rely on setInterval
to check for scrolling periodically.
This approach will work fine as long as there is only a single setInterval
event running, but what if you instead decide to create a separate setInterval
event for each child View
? With only a few child Views
, this still might work, but eventually, too many such intervals will become a drain on the user's CPU, causing performance problems. In the worst case scenario, while your development machine will be able to handle the page, your user's (less powerful) machine might not, causing the user to report bugs that you can't reproduce.
The solution in such cases is straightforward: Don't repeat processing-intensive tasks unnecessarily. In the preceding example, instead of having each child View
update in response to its own setInterval
event, you could start only a single setIonterval
process in the main View
and then, have it trigger updates in your child Views
(possibly by using the pub/sub pattern described in the previous chapter).
3.144.40.42