Welcome!

CMS Authors: Mehdi Daoudi, Rishi Bhargava, Harry Trott, Xenia von Wedel, Carmen Gonzalez

Related Topics: CMS, Java IoT, Machine Learning

CMS: Article

101 on Prototype CSS Selectors

Performance implications of certain CSS Selectors are not specific to a certain JavaScript Library like Prototype

Java Developer Magazine on Ulitzer

Performance implications of certain CSS Selectors are not specific to a certain JavaScript Library like Prototype. I recently blogged about the internals of CSS Selectors in jQuery. The same holds true for every JavaScript library that offers CSS Selectors. Certain lookups can be done by using the native browser functions like getElementById or getElementsByTagName. Lookups by class name are not natively supported in IE and are therefore implemented in JavaScript by iterating through all elements in the DOM - which is obviously much slower than a native implementation.

Expensive Prototype CSS Selector
I recently analyzed some pages of an online retail store that uses Prototype. I used the dynaTrace AJAX Edition to identify the root cause of several slow pages on that web site. I identified two specific examples of CSS Selectors that caused massive overhead on that particular page:

$$("[id^=contentElement]") -> up to 6 seconds on a single page to find all elements that have an id starting with contentElement

$$("div[class=contentDiv]") -> up to 2.3 seconds on a single page to find all div tags with the class contentDiv

Selector Expressions
The flexibility that you get with CSS selectors is great. As you can see from the examples above you can use certain operators to do not only lookup elements by their full id, tag or class name. The following operators are supported (taken from prototype 1.6.1)

  • [id=contentElement] -> finds the element with the id that matches contentElement
  • [id!=contentElement] -> finds all elements that do not match contentElement
  • [id^=contentElement] -> finds all id's that start with contentElement
  • [id$=contentElement] -> finds all id's that end with contentElement
  • [id*=contentElement] -> finds all id's that include contentElement

Additionally to these we have two selectors that allow you to query for elements with attribute values containing hyphen or space separated list values.

  • [sample~=value] -> finds all elements whose sample attribute is a list of space-separate values and one of them has the value "value"
  • [sample|=value]-> finds all elements whose sample attribute is a list of hyphen-separate values and one of them has the value "value"

When using expressions like the ones above (except id=contentElement) Prototype needs to iterate through all DOM elements and manually match the DOM's attribute value with the expected value as there is no native implementation available for this feature by the browser. Depending on the size of your DOM this can cause a huge performance impact.

Sample 1 - Find elements which attributes that start with a certain text
The following screenshot shows the custom JavaScript method that uses the [id=^contentItemContainer] expression to get all elements that have an id attribute starting with contentItemContainer. The page had a total of 3184 DOM elements. The used expression causes Prototype to use getElementsByTagName("*") which returns ALL 3184 elements. Prototype then iterates through all elements. It reads the attribute in question (id) and verifies if it starts with the passed value (contentItemContainer). Additionally to that it reads all sort of other DOM attributes depending on the DOM Element Type (a, td, p, h1, h2, ...) and registers the prototype extension methods (more on this in Sample 2 of this post).

In this example the CSS Expression caused 191454 interactions with the DOM.

Expensive CSS Selector causing 190k DOM Calls

Expensive CSS Selector causing 190k DOM Calls

There are multiple solutions to this problem. One is to find a better way to identify these elements. Looking at the HTML document showed me that all these contentItemContainer elements were in fact DIV tags. Changing the query to $$("div[id=^contentItemContainer]") would have caused Prototype to use getElementsByTagName("div") which would have only returned 178 elements instead of 3184.

In case these elements have different tags this first approach wouldn't work. Limiting the number of DOM elements on the page would be another option to speed up iterating through all elements.

Sample 2 - Find elements by class name
This is the classic example which only holds true for Internet Explorer. As discussed in my previous post about jQuery Selectors - IE does not support a native method to get elements by class name. Using a query like "[className=contentDiv]" would therefore be handled in the same way described in Sample 1 - all DOM elements are iterated to find those elements that match the class name.

What was surprising to me was that the query $$("div[className=contentDiv]") still triggered many more DOM interactions than I expect. Using the "div" tag in the expression solves the problem that not all DOM elements are iterated but just the DIV tags using the native getElementsByTagName to get these elements. On those returned DIV elements Prototype defines it's extension methods like previousSiblings, nextSiblings, match, up, down, ... In my case I had 618 DIV tags. On each of these objects Prototype registered 57 extension methods. This "registration" in the end took most of the time of the item lookup.

Selector registering extension methods
Selector registering extension methods

The query div[className=contentDiv] caused a total of 42415 DOM interactions even though I only had 618 DIV tags on the page where about 200 matched the passed className. I am wondering if there is a way to configure Prototype to not register the additional extension methods in case they are not needed on a particular web page. Any thoughts on this?

Conclusion
As with any JavaScript framework that offers a variety of CSS Selectors you need to know what is actually going on when using them. They are flexible and easy to use. But keep in mind that certain browsers (especially IE) have limitations when it comes to selections by Class Name. Also - the larger the DOM Tree becomes the more overhead you have when using any other lookup method than by id or tagname - in all these cases the JavaScript framework needs to iterate the complete DOM. As always - I am happy for feedback.

Related reading:

  1. Performance Analysis of dynamic JavaScript Menus In my previous post I talked about the impact of...
  2. 101 on jQuery Selector Performance Last week I got to analyze a web page that...
  3. Your Top Links about Web Site/AJAX Performance With the recent work we did for the dynaTrace AJAX...

More Stories By Andreas Grabner

Andreas Grabner has been helping companies improve their application performance for 15+ years. He is a regular contributor within Web Performance and DevOps communities and a prolific speaker at user groups and conferences around the world. Reach him at @grabnerandi

@ThingsExpo Stories
Consumers increasingly expect their electronic "things" to be connected to smart phones, tablets and the Internet. When that thing happens to be a medical device, the risks and benefits of connectivity must be carefully weighed. Once the decision is made that connecting the device is beneficial, medical device manufacturers must design their products to maintain patient safety and prevent compromised personal health information in the face of cybersecurity threats. In his session at @ThingsExpo...
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Grape Up will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...
Detecting internal user threats in the Big Data eco-system is challenging and cumbersome. Many organizations monitor internal usage of the Big Data eco-system using a set of alerts. This is not a scalable process given the increase in the number of alerts with the accelerating growth in data volume and user base. Organizations are increasingly leveraging machine learning to monitor only those data elements that are sensitive and critical, autonomously establish monitoring policies, and to detect...
SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Because IoT devices are deployed in mission-critical environments more than ever before, it’s increasingly imperative they be truly smart. IoT sensors simply stockpiling data isn’t useful. IoT must be artificially and naturally intelligent in order to provide more value In his session at @ThingsExpo, John Crupi, Vice President and Engineering System Architect at Greenwave Systems, will discuss how IoT artificial intelligence (AI) can be carried out via edge analytics and machine learning techn...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, will examine the regulations and provide insight on how it affects technology, challenges the established rules and will usher in new levels of diligence a...
In the enterprise today, connected IoT devices are everywhere – both inside and outside corporate environments. The need to identify, manage, control and secure a quickly growing web of connections and outside devices is making the already challenging task of security even more important, and onerous. In his session at @ThingsExpo, Rich Boyer, CISO and Chief Architect for Security at NTT i3, discussed new ways of thinking and the approaches needed to address the emerging challenges of security i...
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics ...
SYS-CON Events announced today that Datera will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, Cloud Expo and @ThingsExpo are two of the most important technology events of the year. Since its launch over eight years ago, Cloud Expo and @ThingsExpo have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, I provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading the...
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that Elastifile will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Elastifile Cloud File System (ECFS) is software-defined data infrastructure designed for seamless and efficient management of dynamic workloads across heterogeneous environments. Elastifile provides the architecture needed to optimize your hybrid cloud environment, by facilitating efficient...