querySelector vs getElementByID

A quirk of modern Javascript is that we have (at least) two ways of programmatically finding items in the DOM. querySelector is the newer of the two, dating to 2013, and is the more powerful one. It has a fancy syntax, and lets us write complex queries for groups of elements, classes, and subelements. But more powerful isn’t always more betterer.

It turns out that the added complexity means getElementByID is about twice as fast as querySelector. They’re both pretty fast, but I’m going to look into why getElementByID is faster.

In Chrome, getElementByID is actually a relatively simple operation:

First, <a href="https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/dom/node.h?l=622&amp;rcl=2e5f1d247b8d38f84df51458ec78586455273dd8">IsInTreeScope is literally a single integer (enum) comparison just to check if the element target of getElementByID is already inserted in the DOM, in which case this is an easy task.

In this case, all Chrome really has to do is lookup the ID in an ordered map (elements_by_id) which is generally a really simple operation since the map is already constructed. In the event that the element hasn’t already been inserted, it falls back to traversing each descendant node in the target element (with some very slick C++ template/iterator magic).

 

querySelector

querySelector on the other hand, is a bit more work.

It immediately adds the query to a cache, because this is an expensive enough operation:

If it’s not in the cache, then things go off the rails get a bit more interesting, where it runs QueryFirst:

It looks simple, but there is actually an awful lot going on here. Honestly, I can’t tell what’s going on with NthIndexCache, since It’s not actually referenced anywhere, and it’s certainly not doing anything really nuts like _mm_prefetching data (which is a whole ‘nother can o’ worms).Execute however, is a fairly complex function.

It first has a slow path, where it checks every item in the tree with an inner function MatchSelector, a complex function that has to follow many rules:

Screen Shot 2019-08-01 at 12.06.58 PM

There’s an awful lot going on here, it needs to do tons of work! Screencap from: chromium/src/third_party/blink/renderer/core/css/selector_checker.cc

 

Execute then has a (supposedly) faster path where it dispatches on the type of the selector (ID, class) to just “filter” the nodes that match. A bit better.

At the bottom there, FindTraverseRootsAndExecute is an awfully complex method that does a whole bunch more work, but uses some kind of history tracking to cache the work, with some complex bookkeeping logic.

…wait, there’s even more to the function!

Really, this function is just doing fancy stuff to traverse the tree.

It doesn’t really matter

Thankfully, they’re both really fast. Like thousands of operations per millisecond fast. So none of this really matters other than as an exercise in browser internals 🙂

~ by Alexander Riccio on August 1, 2019.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
Lucky's Notes

Notes on math, coding, and other stuff

AbandonedNYC

Abandoned places and history from the five boroughs and beyond.

Open Mind

KIDS' LIVES MATTER so let's stop climate change

I learned it. I share it.

A software engineering blog by György Balássy

Untapped New York

NYC's Secrets and Hidden Gems

Bit9 + Carbon Black Blog

#ArmYourEndpoints

The Electric Chronicles: Power in Flux

If someone ever tells you that you don't need more power, walk away. You don't need that kind of negativity in your life.

Ted's Energy Tips

Practical tips for making your home more comfortable, efficient and safe

love n grace

feel happy, be happy

Recognition, Evaluation, Control

News and views from Diamond Environmental Ltd.

greg tinkers

Sharing the successes and disasters.

Sam Thursfield's Blog

I want music in my life not questions!

Cranraspberry Blog

Sharing the things I love

Biosingularity

Advances in biological systems.

The Embedded Code

Designing From Scratch

Sean Heelan's Blog

Program analysis, verification and security

EduResearcher

Connecting Research, Policy, and Practice in Education

Popehat

A Group Complaint about Law, Liberty, and Leisure

Warners' Stellian Appliance

Home & Kitchen Appliance Blog

Bad Science Debunked

Debunking dangerous junk science found on the Internet. Non-scientist friendly!

4 gravitons

The trials and tribulations of four gravitons and a postdoc

Strange Quark In London

A blog about physics, citylive and much procastination

The Lumber Room

"Consign them to dust and damp by way of preserving them"

In the Dark

A blog about the Universe, and all that surrounds it

andrea elizabeth

passionate - vibrant - ambitious

Probably Dance

I can program and like games

a totally unnecessary blog

paolo severini's waste of bandwidth

Musing Mortoray

Programming and Life

PJ Naughter's space

Musings on Native mode development on Windows using C++

  Bartosz Milewski's Programming Cafe

Category Theory, Haskell, Concurrency, C++

Brandon's Thoughts

Thoughts on programming

David Crocker's Verification Blog

Formal verification of C/C++ code for critical systems

10 Minute Astronomy

Stargazing for people who think they don't have time for stargazing.

One Dev Job

notes of an interactive developer

Enterprise Architect, IoT, Cloud, Mobile Apps, Technology Evangelist, Technical Pre-Sales, Business Evangelist, Speaker

Coder/Architect for IoT, Cloud Technologies and Mobile Apps, Azure Cloud, Amazon Cloud, Windows Phone 10 Apps, iPhone Apps, Scrum Master, Business Evangelist, Mobile apps developer in iOS and Windows 10 UWP, Azure IoT Hub, Machine Learning, Stream Analytics, Azure Mobile Service, APM Tools

The Angry Technician

No, the Internet is not broken.

Kenny Kerr

Author • Systems programmer • Creator of C++/WinRT • Engineer on the Windows team at Microsoft • Romans 1:16

IT affinity!

The Ultimate Question of Life, the Universe, and Everything is answered somwhere else. This is just about IT.

Eat/Play/Hate

The ramblings of a crazed mind

Molecular Musings

Development blog of the Molecule Engine

%d bloggers like this: