4

Based on the answers to another mine question (this: How to make children auto fit parent's width only with CSS?), I'm thinking which is the best jQuery approach to solve the problem regarding performance.

Block 1: find all DOM elements when needed:

$("div.parent a").css("width", $("div.parent").width() / $("div.parent a").length - 2);

Block 2: find only DOM children, use each(), parent() and siblings():

$("div.parent a").each(function() {
    $(this).css("width", $(this).parent().width() / $(this).siblings().length - 2);
});

Block 3: find DOM parent first, use each() and find children based on context:

$("div.parent").each(function() {
    $("a", this).css("width", $(this).width() / $("a", this).length - 2);
});

Here is the Fiddle if someone wants to test: http://jsfiddle.net/ErickPetru/6nSEj/3/

So, which block is better? And why?

Community
  • 1
  • 1
Erick Petrucelli
  • 14,386
  • 8
  • 64
  • 84

3 Answers3

3

I would pre-query the elements, like so:

// find the elements you want to resize
var $links = $("div.parent a");

// resize them, and use the parent width
$links.width($links.parent().width() / $links.length - 2);

This way you're looking up the links, and looking up to the parent, only once. There's no looping, and there's no redundant queries.

Here's an example:

http://jsfiddle.net/xixionia/Gsek5/

cwharris
  • 17,835
  • 4
  • 44
  • 64
3

Using FireBug profiling:

  • block 1: 8.466 ms, 372 calls
  • block 2: 10.130 ms, 526 calls
  • block 3: 8.560 ms, 383 calls

also xixonia's answer was the fastest

  • xixonia: 8.205 ms, 369 calls

In order of speed:

  1. xixonia's
  2. block 1
  3. block 3

wouldn't even use block 2

MikeM
  • 27,227
  • 4
  • 64
  • 80
0

I would say Block 1 would be best due to the fact that it does not require a loop,

You can also try this:

$("div.parent a").css({
    width: $(this).parent().width() / $(this).siblings().length - 2)
});
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • "css({...})" does not change the scope of "this", so $(this) would refer to the jQuery object enclosing the local "this", and not the individual links. – cwharris May 02 '11 at 16:15
  • I think jQuery really could change the scope of `this` for `css()` and many other methods. But [xixonia](http://stackoverflow.com/users/696056/xixonia) is right: doesn't works. – Erick Petrucelli May 02 '11 at 16:40