I have an array of data that is returned as a JSON response. The data will be regularly updated, and will also be accessed very frequently.
The data contains a list of comments/replies for each song on display and is accessed when the user hovers over a particular element, and the specific comment/reply is then rendered to a template.
The list of songs is also dynamically filterable and the array will therefore be constantly updating.
Given the frequent access and updates of this data which of the following would be considered best practice:-
A. Store the whole array in a global variable and constantly manipulate it/access it.
or
B. Store the array in the DOM using jQuery’s $.data method and access it that way.
Which would be best and why… If option A please bear in mind that the variable will need to be held in memory throughout the users session. Also is there anything I need to watch out for in terms of potential memory leaks etc?
EDIT: Just to provide some more information: On average I would expect the data to be between 2-5kb at any given time.
I’m going to have to say option B here. While the performance benefits of manipulating a pure array sounds really attractive, from what it sounds like, your usage of the data sort of necessitates relating your data to the individual DOM elements they apply to.
With
$.data, you’re attaching data to the element that they pertain to. Imagine the workflow of yourhoverevent:It’s certainly cleaner, and I can’t imagine how you’re making your DOM elements remember their associated data in the global array, save from plugging it on the DOM element themselves via an attribute, or having an object reference somewhere.
Secondly, global objects are evil. To some significant, prone-to-argument-and-debate-flamebait extent.
Thirdly, it sounds like your song elements are sorting and filtering on the DOM themselves. If you attach your data via
$.data, those get sorted and filtered along with the DOM elements without any additional tracking. A song element has to be erased from the DOM? Just call.remove()on it — the associated gets deleted as well. Free functionality!Lastly,
$.datais also optimized to prevent circular references and memory leaks as well (correct me if I’m mistaken on that one).Besides, 2-5kb of data doesn’t sound like a whole lot.
Just my two cents.