Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hasChildNodes vs firstChild

while (div.hasChildNodes()) {
    fragment.appendChild(div.firstChild)
}

while (div.firstChild) {
    fragment.appendChild(div.firstChild)
}

Comparing the two pieces of pseudo code above, they both append each child of div to fragment until there are no more children.

  1. When would you favour hasChildNodes or firstChild they seem identical.
  2. If the APIs are so similar then why do they both exist. Why does hasChildNodes() exist when I can just coerce firstChild from null to false
like image 983
Raynos Avatar asked Apr 13 '12 01:04

Raynos


2 Answers

a) micro-optimization!

b) Although it seems to be common practice, I'm not fond of relying on null/non-null values being used as a substitute for false/true. It's a space saver that's unnecessary with server compression enabled (and can sometimes call subtle bugs). Opt for clarity every time, unless it's demonstrated to be causing bottlenecks.

I'd go for the first option, because it explains your intent perfectly.

like image 187
spender Avatar answered Nov 02 '22 16:11

spender


There's no functional difference between your two implementations. Both generate the same results in all circumstances.

If you wanted to pursue whether there was a performance difference between the two, you would have to run performance tests on the desired target browsers to see if there was a meaningful difference.

Here's a performance test of the two. It appears to be browser-specific for which one is faster. hasChildNodes() is significantly faster in Chrome, but firstChild is a little bit faster in IE9 and Firefox.

enter image description here

like image 4
jfriend00 Avatar answered Nov 02 '22 15:11

jfriend00