I want to understand the best way to improve the performance of jQuery code.
Actually, I know how to cache the jQuery selectors to not touch the DOM multiple times as follow:
The worst way
$('.selector').text('Text');
$('.selector').text('New Text');
The better way
var elem = document.querySelectorAll('.selector');
$(elem).text('Text');
$(elem).text('New Text');
The best way
var $elem = $('.selector');
$elem.text('Text');
$elem.text('New Text');
First Question: Why the third method is faster than the second, and what actually $(elem)
do here?
Second Question: When I use .data()
in jQuery, I access the internal cache, and don't touch the DOM, so what's the internal cache in JavaScript?
Third is faster because you put a jQuery element into a variable (RAM) so you can access it directly and jQuery doesn't have to parse the DOM each time you want access it. Think of it like you want to edit a file, you don't want to use a search engine each time you touch it, you just let it open. In your exemple, elem
is an HTML element and jQuery finds out wich element your referring to with $(elem)
.
The .data()
method, don't touch the HTML element because it doesn't need to. It just put some data into RAM because it's faster than writing/reading it into the HTML element each time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.