LoginSignup
21
21

More than 5 years have passed since last update.

jQueryのセレクタの検索速度を簡単に調べた

Posted at

IntelliJ IDEAでjQueryを書いているとたまにInefficient jQuery usageと表示されることがある。

Inefficient jQuery usage

ざっくり言うと「これ効率悪いから、ID部分とクラスセレクタ部分を分割しようぜ」ということらしいのだが、ホンマでっか?

というわけで以下のコートで調べてみた。

<!DOCTYPE html>
<html>
  <head>
    <title>Sample</title>
  </head>
  <body>
    <div id="div-id">
      <span class="span-class1">hogehoge</span>
      <span class="span-class1">fugafuga</span>
      <span class="span-class2">piyopiyo</span>
      <span class="span-class2">foo</span>
      <span class="span-class3">bar</span>
      <span class="span-class3">foobar</span>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script>
    'use strict';
    function sameSelector() {
      console.time('Include same selector');
      for (let i = 0; i < 100000; i++) $('#div-id .span-class3');
      console.timeEnd('Include same selector');
    }
    function useFine() {
      console.time('Use find');
      for (let i = 0; i < 100000; i++) $('#div-id').find('.span-class3');
      console.timeEnd('Use find');
    }
    </script>
  </body>
</html>

結果は、

Include same selector: 640.185ms
Use find: 569.863ms

おー、ホンマや。

ちなみに生のJavaScriptだとどうなんだろう?

以下のコードを実行。

function querySelector() {
  console.time('Query Selector');
  for (let i = 0; i < 100000; i++) document.querySelectorAll('#div-id .span-class3');
  console.timeEnd('Query Selector');
}
function getElements() {
  console.time('Get elements');
  for (let i = 0; i < 100000; i++) document.getElementById('div-id').getElementsByClassName('span-class3');
  console.timeEnd('Get elements');
}
Query Selector: 98.683ms
Get elements: 12.100ms

やっぱり早いなぁ。

21
21
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
21
21