Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Cache jQuery Selections</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style>#list li{display:inline-block;margin:2px;padding:4px 6px;border:1px solid #ccc}</style> </head> <body> <ul id="list"></ul> <button id="fill">Fill 200 items</button> <pre id="out"></pre> <script> function time(label, fn){ var t = performance.now(); fn(); $("#out").append(label + ": " + (performance.now()-t).toFixed(2)+"ms\n"); } $("#fill").on("click", function(){ $("#list").empty(); time("without cache", function(){ for(var i=0;i<200;i++){ $("#list").append("<li>"+i+"</li>"); } }); $("#list").empty(); time("with cache", function(){ var $list = $("#list"); var html = []; for(var i=0;i<200;i++){ html.push("<li>"+i+"</li>"); } $list.append(html.join("")); }); }); </script> </body> </html>
Output