1

I have a scenario in which I know that the div I'm looking for is exactly two levels deep.

Is it more efficient to use:

$('#mydiv').find('.myselector')

or

$('#mydiv').children().children('.myselector')
j08691
  • 204,283
  • 31
  • 260
  • 272
ForOhFor
  • 786
  • 10
  • 16
  • 2
    Have you tried it? Should not be to hard to analyze... – Constantinius Jan 27 '14 at 20:03
  • 2
    It's more efficient to ditch jQuery. You should always do that if you are looking for efficiency. – bjb568 Jan 27 '14 at 20:03
  • 1
    Prepare a test and let people check! http://jsperf.com/ – Jakub Matczak Jan 27 '14 at 20:03
  • 4
    Either way, you'll probably AT MOST shave off a few nanoseconds - I'd say use whichever makes more sense to you and your code... – FastTrack Jan 27 '14 at 20:05
  • @FastTrack I though .find() was significantly less efficient (relatively speaking) – ForOhFor Jan 27 '14 at 20:06
  • 1
    @ForOhFor define "significantly" for me if you don't mind... Unless you're cycling through thousands upon thousands of DOM elements, you/your users won't notice a difference. – FastTrack Jan 27 '14 at 20:06
  • If you're looking for efficiency, I'd definitely say go for pure JS and search by xpath if you know where the element is – Mike M Jan 27 '14 at 20:07
  • 1
    There's already an answer for this: [What is fastest children() or find() in jQuery?](http://stackoverflow.com/questions/648004/what-is-fastest-children-or-find-in-jquery) – alexP Jan 27 '14 at 20:11
  • For those advocating vanillaJS, you're right only if there's not already a really good reason to use jQuery. Once it's already in, might as well use it. Besides, a vanilla js answer doesn't really answer the question, does it? – shubniggurath Jan 27 '14 at 20:12
  • @alexP Thanks! I guess according to that question its more worthwhile to use .find() because the diff is so small to begin with – ForOhFor Jan 27 '14 at 20:13
  • 1
    @shubniggurath exactly, i already need to use jQuery.. i've got a ton of other stuff i'm using it for already on the site (and i've also simplified the situation i need it for) – ForOhFor Jan 27 '14 at 20:14
  • 1
    $('#mydiv > * > .myselector') or $('#mydiv .myselector') – Tony Jan 27 '14 at 20:22

2 Answers2

7

Use your console to check. First check your first suggestion:

console.time('benchmark');
for (var i=0; i<1000; i++) {
  var $elem = $('#mydiv').find('.myselector');
}
console.timeEnd('benchmark');

Now do the same for your second suggestion:

console.time('benchmark');
for (var i=0; i<1000; i++) {
  var $elem = $('#mydiv').children().children('.myselector');
}
console.timeEnd('benchmark');

Run both versions a few times to really check if there is a significant difference. Use this way of testing to optimise your selectors.

meavo
  • 1,042
  • 1
  • 7
  • 16
  • Thanks.. totally blanked on trying that! Just ran it and .children().children() took 160ms or more and .find() took less than 10ms each time! I'm going with .find() – ForOhFor Jan 27 '14 at 20:32
  • Cool; did you maybe also tried the vanilla JS version of @Niet the Dark Absol? Just curious how much faster it is ... – meavo Jan 27 '14 at 20:40
  • 1
    Just on a side note, I can't find it, but there was a really nice jsPerf written somewhere with comparisons of the different selector approaches in jQuery and `find()` is almost always the quickest. Additionally, `.filter()` tends to go faster than using pseudo-selectors. – talemyn Jan 27 '14 at 20:42
  • @ForOhFor - I think this is the jsPerf Test that I was thinking of in the comment above: http://jsperf.com/jquery-selectors-context/70 The "Browserscope" isn't showing all of the browsers, so you may need to just run it a few times in different browsers to get an idea of the differences, if you are interested. – talemyn Jan 27 '14 at 20:56
  • An oldie but goodie. Probably one of the most useful console scripts I'll ever find. – gavsiu May 02 '17 at 19:17
1

Try this instead:

var elems = document.getElementById('mydiv').querySelectorAll(".myselector");

A comparison of jQuery versus a few Vanilla JS ideas I had.


EDIT: For IE7 support:

var container = document.getElementById('mydiv'), elems = [],
    firstlevel = container.children, l = firstlevel.length,
    secondlevel, m, i, j;
for( i=0; i<l; i++) {
    secondlevel = firstlevel[i].children;
    m = secondlevel.length;
    for( j=0; j<m; j++) {
        if( secondlevel[j].className.match(/\bmyselector\b/)) {
            elems.push(secondlevel[j]);
        }
    }
}

... Yeah, not pretty! But still faster than jQuery!

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • I don't think he wants a JS answer here... according to the title, the OP wants to use jQuery, not pure JS – FastTrack Jan 27 '14 at 20:09
  • 4
    @FastTrack Well that's just stupid, in my opinion :p Then again, I find jQuery to be stupid: if you don't know Vanilla JS then you shouldn't use a tool like that, and if you do know Vanilla JS then you don't *need* a tool like that. – Niet the Dark Absol Jan 27 '14 at 20:11
  • 2
    @NiettheDarkAbsol - you forgot "Now get off my lawn, you pesky kids!" ;) – talemyn Jan 27 '14 at 20:12
  • 1
    @talemyn Hah, yes, call me old-fashioned (even though I'm only 21) but I write my own set of precision tools for the job I need and maximum efficiency :) I guess that's what comes of having a website that constantly sees hundreds of users online at once... – Niet the Dark Absol Jan 27 '14 at 20:14
  • 1
    I know vanilla js. jQuery is a huge help for medium to large projects. It's not a matter of a replacement for actual vanilla js knowledge, it's a supplement to it. It's more stuff to know, not less. Might as well say C++ is for dolts who can't write assembly. – shubniggurath Jan 27 '14 at 20:15
  • There are certainly tasks for which jQuery is nice. However, if you can do it relatively easily with vanilla JS, then using jQuery is wasteful. I'd agree that this is a task where vanilla JS would be easy to use. – crush Jan 27 '14 at 20:16
  • @shubniggurath Or the standard library is for dolts who don't know how to use memcpy – crush Jan 27 '14 at 20:17
  • 2
    @NiettheDarkAbsol I've been working with pure JS for over 6 years now and jQuery is a godsend for medium to large-sized projects. I can't even fathom writing some of the UI components on the larger projects I've been on with vanilla JS... it would have taken AT LEAST twice as long with AT LEAST twice as many lines of script – FastTrack Jan 27 '14 at 20:18
  • 3
    My site still has to work on IE7 (yeah, i know...) so instead of worrying about whats going to break in which IE i use jQuery – ForOhFor Jan 27 '14 at 20:18
  • But you don't know the whole picture, do you? You see one question - he may well have thousands of lines of code, varying complexity. – shubniggurath Jan 27 '14 at 20:18
  • @ForOhFor Oh wow... I feel sorry for you. In that case, yeah, jQuery will be much simpler... Although personally I'd still prefer to build my own shim :p Let me see... – Niet the Dark Absol Jan 27 '14 at 20:19
  • 1
    I'm with @shubniggurath . . . each has their own use and there is nothing ever wrong with knowing multiple ways of doing things. I work in consulting, so I never know what my target audience will be or the standards of the client . . . I need to be able to handle whatever is thrown at me. Shoot, two projects ago, the site I helped develop had to support IE5.5! – talemyn Jan 27 '14 at 20:21
  • I've edited my answer with code that allows for IE7 support. It's still faster than jQuery! – Niet the Dark Absol Jan 27 '14 at 20:23
  • 1
    @NiettheDarkAbsol - BTW, thanks for making me feel old . . . if you're 21, that means I started in web development when you were about 1 year old . . . actually, probably less than 1. :( – talemyn Jan 27 '14 at 20:25
  • 1
    @shubniggurath - A friend of mine grabbed me from my room in college because "I had to check something out in the computer lab". It was Mosaic, and I've been hooked on web development ever since. :) – talemyn Jan 27 '14 at 20:30
  • @Tony Why? Because people can't be arsed to write efficient code? :p That's why we have to download gigabytes of data and have computers with just as much RAM just to play Skyrim XD ... I wonder what Skyrim would look like if it only had the power to look like Descent... – Niet the Dark Absol Jan 27 '14 at 20:31
  • Descent was an awesome game, written by people who knew what they were doing with the limited resources they had... Damn it, now I want to go play it again! – Niet the Dark Absol Jan 27 '14 at 20:33
  • 1
    @NiettheDarkAbsol It's not that people can't write decent code, but the advantage gained(faster development) in the real world by using jQuery outweighs the cost of using "better code". You seem to know your stuff so I am sure you know the advantages of using jQuery on projects that must stick to a budget. Vanilla JS has it place but in large projects I will take jQuery 100 times over. Besides Healthcare.gov uses jQuery. =D – Tony Jan 27 '14 at 20:37
  • There's actually a psychological reason I don't use jQuery. If I use it and something goes wrong, I'll just blame it on some fault in jQuery. However, if I write every line of code myself, I have no such escape ;) – Niet the Dark Absol Jan 27 '14 at 20:38
  • I think the point here is that if you aren't using jQuery wisely, mixing it with vanilla JS where appropriate, then you're not doing it right. There's not point in doing `$('#myElement').attr('href', 'something.html')` when you could easily do `document.getElementById('myElement').setAttribute('href', 'something.html');` for the brevity that jQuery gives, you lose a ton of performance and waste quite a bit of memory (though it will be gc'd when needed). – crush Jan 27 '14 at 20:54
  • 1
    @talemyn - remember the Lynx browser? – shubniggurath Jan 27 '14 at 21:31
  • 1
    @shubniggurath - all too well . . . used to have to make two versions of every web page because of that thing. LOL – talemyn Jan 27 '14 at 21:39
  • @talemyn - and with some of the more recent HTML5 implementations, sometimes you still get to! – shubniggurath Jan 27 '14 at 22:28
  • @shubniggurath - which is why I never get to play with HTML5. :( – talemyn Jan 28 '14 at 02:28
  • 1
    @NiettheDarkAbsol that edit is exactly why jQuery is in existence... you fail to realize (and maybe it's because of your inexperience working with a team of developers in large-scale projects) that writing code isn't all about "efficiency". At some point, efficiency will out-weigh readability and then you're left with code that is difficult to discern and causes headache after headache for the developers who come after you and have to weed through your convoluted spaghetti code. – FastTrack Jan 29 '14 at 13:14
  • @FastTrack Is that not what comments are for? Besides, this code would be put in a function somewhere. – Niet the Dark Absol Jan 29 '14 at 15:59