LoginSignup
0
0

More than 5 years have passed since last update.

【getElementsByClassName】CLASSの検索どっちが早い!?【querySelector】

Posted at

業務でjavascriptを書いていたらふと疑問に感じたので実験してみました。

実験方法

Yahoo!トップページの中のクラス「clfix」の存在確認を1000回1セットで10回実施。
1セットごとに念のためブラウザのキャッシュクリアリロード。

getElementsByClassName('CLASSNAME')

console.time('計測ByClassName')
for(var i=0; i<1000; i++){
  if(document.getElementsByClassName('clfix') != null){
    console.log('exist');
  }
}
console.timeEnd('計測ByClassName')

実験結果

test result average
1 134s 0.134s
2 125s 0.125s
3 126s 0.126s
4 130s 0.130s
5 127s 0.127s
6 114s 0.114s
7 134s 0.134s
8 136s 0.136s
9 142s 0.142s
10 121s 0.121s
total 1289s 0.1289s

querySelector('.CLASSNAME')

console.time('計測querySelector')
for(var i=0; i<1000; i++){
  if(document.querySelector('.clfix') != null){
    console.log('exist');
  }
}
console.timeEnd('計測querySelector')

実験結果

test result average
1 124s 0.124s
2 142s 0.142s
3 137s 0.137s
4 139s 0.139s
5 129s 0.129s
6 126s 0.126s
7 118s 0.118s
8 142s 0.142s
9 140s 0.140s
10 131s 0.131s
total 1328s 01328.s

結論

まぁCLASS検索専用の方がそりゃ早いよねw
スッキリ!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0