To make it clear what I'm asking, here is my example (fiddle).
I have a list of ~500 random names. I have an input at the top that has live-style searching. On every keyup
, the value of the input is taken, and every item in the list is matched against it. Items that don't match are hidden.
Subjectively, the performance is okay, but not great. If you type quickly there is a noticeable pause before the list updates. I haven't profiled the code, but the bottleneck is almost certainly the changes to the DOM and the reflows it causes.
I wonder if it's possible to “queue up” these changes and only actually apply them at the end of the loop. So it would be one giant reflow and not lots of little ones.
In another version of the fiddle, I used a RegExp to get more fancy with the matching and presentation. Even though I'm using more DOM manipulation in this one (adding/removing tags to enable match highlighting) the performance feels about the same. I did also try adding visible/hidden classes in CSS and just setting the elements' className
to that because that is supposed to be better performing (search for javascript reflows & repaints stubbornella—I can't post more than 2 links) but in my testing (Firefox 54) I found it was worse. So I don't know what's going on there.
What I guess I'm actually asking is: how do I make this code faster?
requestAnimationFrame
to schedule the DOM change though – ByssinosisinnerText
, it takes into account the styling of the element - and when the content is hidden,innerText
returns the empty string. UsetextContent
instead. Also, usinginnerHTML
500 times is kinda slow as well, it would be better to cache the nodes and texts and only alter their contents. – Byssinosis