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
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It’s clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. Tha...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, 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. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
SYS-CON Events announced today that TidalScale 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. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant th...
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
SYS-CON Events announced today that Golden Gate University 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. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, 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. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...