简体   繁体   English

classList.Add 的 js 优化

[英]js optimization for classList.Add

I'm trying to squeeze as much performance out of my js as possible.我试图从我的 js 中挤出尽可能多的性能。 I need to make sure an element has a class assigned.我需要确保一个元素分配了一个类。 Is it faster to check and only assign if it's not there, or always assign even if it's already there?检查并仅在它不存在时才分配,还是即使它已经存在也总是分配更快?

In other words, which is faster换句话说,哪个更快

if (!element.classList.contains('class')) element.classList.add('class');

or always do this或者总是这样做

element.classList.add('class');

The class is already there about 10% of the time.该类已经有大约 10% 的时间在那里。

The element.classList.add checks if class is already there anyway. element.classList.add检查类是否已经存在。 Try to add same class twice, it will not be added.尝试添加相同的类两次,它不会被添加。 I am positive that the Browser is by far quicker than js to check if should add.我很肯定浏览器在检查是否应该添加方面比 js 快得多。 So, go ahead and add without checking.所以,继续添加而不检查。

Someone suggested using jsperf.com.有人建议使用 jsperf.com。 Here is the sample https://jsperf.com/classlist-add-vs-classlist-contains/1这是示例https://jsperf.com/classlist-add-vs-classlist-contains/1

Looks like checking first is about 5% faster than just adding看起来先检查比仅仅添加快 5%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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