简体   繁体   中英

Most efficient way to add remove classes with JavaScript

I am curious if anyone knows which of these is more efficient, I am only concerned with Firefox as a browser and do not need to know that this code doesn't work in IE, etc...

Basically I am showing and hiding DOM elements based on an input field's value, an instant search if you will. I need to show or hide a "nothing found" element if no search results are shown. I am curious if it is cheaper (more efficient) to check if the "nothing found" element is in the proper state before modifying its class attribute, or to just modify the class attribute.

Question: should I remove/add the hidden class every time the function is run, even if there is no change in the element's class attribute?

if (shown_count > 0) {
    element.classList.add('hidden');
}
else {
    element.classList.remove('hidden');
}

or should I check to see if the element needs its class attribute updated before actually updating it?

if (shown_count > 0) {
    if (element.classList.contains('hidden') == false) {
         element.classList.add('hidden');
    }
}
else {
    if (element.classList.contains('hidden')) {
         element.classList.remove('hidden');
    }
}

I think the existence check is already done by the native code, so you do not need to check it again.

So let's take a look at the source code( Note: classList is DOMTokenList object)

String DOMTokenList::addToken(const AtomicString& input, const AtomicString& token)
{
    if (input.isEmpty())
        return token;

    StringBuilder builder;
    builder.append(input);
    if (input[input.length()-1] != ' ')   // <--- check happens here
        builder.append(' ');
    builder.append(token);
    return builder.toString();
}

source comes from the WebKit's WebCore

After running some tests on jsperf the answer is simply that the first option is quicker. Likely due to xdazz's answer, that the classList.add method does the check already.

Here is a link to the performance test: http://jsperf.com/add-remove-class-performanci

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM