SlideShare una empresa de Scribd logo
1 de 55
Descargar para leer sin conexión
var title = “DOM Performance”; 
Nov 23, 2014 
Nov 23, 
2014 
Sofia 
var info = { 
name: “Hristo Chakarov”, 
otherOptional: undefined 
};
Nov 23, 
2014 
agenda(); 
• Why performance is so important 
• Event delegation 
• Stylesheet manipulation 
• DOM creation 
• DOM destruction 
• Questions
Nov 23, 
2014 
Performance 
Why so important?
Nov 23, 
2014
Nov 23, 
2014 
Why performance matters? 
Good performance improves User Experience 
(UX) 
• Slow performance is very obvious 
• Users don’t enjoy waiting
Nov 23, 
2014
Nov 23, 
2014 
DOM operations are heavy 
• createElement is most expensive 
• The more elements you need to operate 
with, the worse performance you get 
o Event handling 
o Styling
Nov 23, 
2014 
Event Delegation 
What is it & how it affects performance
Nov 23, 
2014
Handling events on a single element 
Nov 23, 
2014 
var cell = document.querySelector('td'); 
cell.addEventListener( 'click', function ( event ) { 
// mark the cell in blue 
this.style.background = 'blue'; 
});
Handling events on multiple elements 
Nov 23, 
2014 
// imagine that we have 30’000 or more <td> elements… 
var cells = document.querySelectorAll('td'); 
// create single event handler 
var handler = function ( event ) { 
// mark the cell in blue 
this.style.background = 'blue'; 
}; 
for ( var i=0, l=cells.length; i<l; i += 1 ) { 
// add listener to every single cell... 
cells[i].addEventListener( 'click', handler ); 
}
Nov 23, 
2014 
Delegate?
Nov 23, 
2014 
Event delegation 
Event delegation allows you to avoid adding 
event listeners to specific nodes; instead, 
the event listener is added to one parent.
Nov 23, 
2014 
Delegate event 
// delegate click event to the table 
var table = document.querySelector('table'); 
table.addEventListener( 'click', function ( event ) { 
// `this` is the whole <table>, but `event.target` is 
the cell that has been clicked 
event.target.style.background = 'blue'; 
});
Nov 23, 
2014 
Delegate event 
// delegate click event to the table 
var table = document.querySelector('table'); 
table.addEventListener( 'click', function ( event ) { 
// `this` is the whole <table>, but `event.target` 
//is the element that has been clicked 
// find out the <td> element 
var cell = event.target; 
while ( cell && cell.tagName != 'TD' && cell != this ) { 
cell = cell.parentNode; 
} 
cell.style.background = 'blue'; 
});
Event delegation performance results 
Nov 23, 
2014 
http://jsperf.com/delegate-event
Event delegation - pros & cons 
• Drastically increases performance 
• It’s alive! Elements about to be appended 
later automagically delegate the event to 
the parent 
• Not suitable for some kinds of events 
Nov 23, 
2014 
o mouseenter/mouseleave 
o mouseover/mouseout
Nov 23, 
2014 
Styling 
How can we style thousands of elements without reducing 
the performance?
Nov 23, 
2014
Nov 23, 
2014 
Styling elements 
document.querySelector('tr').style.height = '75px'; 
// what if we have 100’000 rows? 
[].slice.call( 
document.querySelectorAll('tr') 
).forEach( function ( tr ) { 
tr.style.height = '75px'; 
});
Nov 23, 
2014
Nov 23, 
2014 
Using a style sheet 
document.head.appendChild( 
document.createElement('style') 
).innerHTML = 'tr { height: 75px }';
Nov 23, 
2014 
Stylesheet API 
// get the styleSheet object 
var sheet = document.querySelector('style').sheet; 
// insert new CSS rule at the bottom of the stylesheet 
sheet.insertRule( 'tr { height: 75px }', 
sheet.cssRules.length ); 
// delete the top CSS rule 
sheet.deleteRule( 0 );
Still supporting IE8? No problem! 
https://github.com/ickata/utilities/blob/ 
master/JavaScript/Source/stylesheet-api.js 
Nov 23, 
2014
Nov 23, 
2014 
Styling performance results 
http://jsperf.com/stylesheet-api
Nov 23, 
2014 
Stylesheet API - pros & cons 
• Drastically increases performance 
• It’s alive! Elements about to be appended 
later automagically inherit styles 
• Not cross-browser 
o insertRule/addRule 
o deleteRule/removeRule 
o cssRules/rules 
o innerHTML/styleSheet.cssText
Nov 23, 
2014 
DOM creation 
Interactive SPA requires a lot of new DOM elements
createElement vs cloneNode vs innerHTML 
• createElement is the slowest DOM 
operation 
• cloning a single node or a structure via 
cloneNode is much faster 
• old-school innerHTML is much faster as 
well 
Nov 23, 
2014 
o innerHTML is not approved by W3, but all 
browsers support it
DOM creation performance results 
Nov 23, 
2014 
http://jsperf.com/dom-creation-4
Nov 23, 
2014
Can we get even better results? 
Nov 23, 
2014
Nov 23, 
2014 
DocumentFragment 
DocumentFragment is a lightweight 
container that can hold DOM nodes. Various 
operations, such as inserting nodes as 
children of another Node, may take 
DocumentFragment objects as arguments; 
this results in all the child nodes of the 
DocumentFragment being moved to the child 
list of this node.
Nov 23, 
2014 
Clone a DocumentFragment 
If we append 10 elements to a 
DocumentFragment, and then append to the 
same fragment a clone of it, as a result the 
fragment will contain 20 elements. 
If we repeat the fragment clone/append 
operations 2 more times - we will get a 
fragment with a total of 80 elements!
Cloning fragments dramatically 
reduces the # of operations! 
Nov 23, 
2014
Nov 23, 
2014 
Clone fragments algorithm 
• Create desired number of elements using 
DocumentFragment & cloneNode 
• Use less operations as possible
Nov 23, 
2014 
Clone fragments algorithm 
• Reduce the total # of desired elements by 
division of 2 until we get odd number or 
the simple numbers 2 or 3 
• Subtract 1 from odd numbers & continue 
division by 2 unless result is 2 or 3. Store 
the step index for later (when we will have 
to add +1)
Nov 23, 
2014 
Clone fragments algorithm 
• Create 2 or 3 clones of the source element 
• Multiply by 2 until we reach the desired 
number of cloned elements 
• Add +1 to the result on each stored step
Clone fragments algorithm example 
1000 = 
((((3 * 2 + 1) * 2 + 1) * 2 + 1) * 2 * 2 + 1) * 2 * 2 * 2 
Nov 23, 
2014
Nov 23, 
2014 
cloneMultiple 
https://github.com/ickata/utilities/blob/ 
master/JavaScript/Source/element-clone-multiple. 
js
Nov 23, 
2014 
cloneNode vs cloneMultiple
cloneNode vs cloneMultiple - Chrome 
Nov 23, 
2014
cloneNode vs cloneMultiple - Firefox 
Nov 23, 
2014
cloneNode vs cloneMultiple - IE8 
Nov 23, 
2014
Nov 23, 
2014 
cloneMultiple - summary 
• Makes sense to use for large amount of 
elements 
• Reduces # of DOM operations to clone 
elements 
• The more elements we clone, the less # of 
operations we have! 
o to clone 1000 elements, we need only 33 
operations! 
o to clone 2000 - we need only 35!
Nov 23, 
2014
Nov 23, 
2014 
DOM destruction
Nov 23, 
2014 
Destroying elements 
// remove a single element 
parentNode.removeChild( element ); 
// remove all descendants 
parentNode.innerHTML = ""; // wow.. that’s heavy
Nov 23, 
2014 
Destroying elements 
• innerHTML destroys all elements one by 
one 
• removeChild destroys the element with all 
its descendants 
• design your system in a way so when you 
need to remove multiple elements you 
remove their parent 
o that’s a single operation!
Nov 23, 
2014 
Resources
Nov 23, 
2014 
Resources 
• DocumentFragment 
• Performance Tests 
o Event Delegation 
o Stylesheet Manipulation 
o DOM Creation 
• DOM Performance (BG)
Nov 23, 
2014
Nov 23, 
2014 
Questions?
Nov 23, 
2014 
Upcoming events 
ISTA Conference 26-27 November 
http://istabg.org/ 
Stay tuned for 2015: 
Azure Bootcamp http://azure-camp. 
eu/ 
UXify Bulgaria http://uxify.org/ 
SQLSaturday https:// 
www.sqlsaturday.com/ 
and more js.next();
Nov 23, 
2014 
Thanks to our Sponsors: 
Diamond Sponsor: 
Hosting partner: 
Gold Sponsors: 
Silver Sponsors: 
Technological 
Partners: 
Bronze Sponsors: 
Swag Sponsors: 
Media Partners:
Nov 23, 
2014 
Thanks for listening! 
• Hristo Chakarov 
• Front-end architect 
• SiteKreator 
• JavaScript trainer 
• IT Academy 
• Photographer 
• @github 
• +HristoChakarov

Más contenido relacionado

La actualidad más candente

Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Xamarin
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, ChileJavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, MontevideoJavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos AiresJavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
Robert Nyman
 

La actualidad más candente (20)

Introduction to Service Workers | Matteo Manchi
Introduction to Service Workers | Matteo ManchiIntroduction to Service Workers | Matteo Manchi
Introduction to Service Workers | Matteo Manchi
 
Core animation
Core animationCore animation
Core animation
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
 
iOS Memory Management Basics
iOS Memory Management BasicsiOS Memory Management Basics
iOS Memory Management Basics
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
 
Digesting jQuery
Digesting jQueryDigesting jQuery
Digesting jQuery
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
iOS Memory Management
iOS Memory ManagementiOS Memory Management
iOS Memory Management
 
Deceptive simplicity of async and await
Deceptive simplicity of async and awaitDeceptive simplicity of async and await
Deceptive simplicity of async and await
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
Drupal, meet Assetic
Drupal, meet AsseticDrupal, meet Assetic
Drupal, meet Assetic
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, ChileJavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, MontevideoJavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos AiresJavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
Yavorsky
YavorskyYavorsky
Yavorsky
 
Ios - Introduction to memory management
Ios - Introduction to memory managementIos - Introduction to memory management
Ios - Introduction to memory management
 
Whats new in iOS5
Whats new in iOS5Whats new in iOS5
Whats new in iOS5
 
JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015
 

Destacado

Choosing the best JavaScript framework/library/toolkit
Choosing the best JavaScript framework/library/toolkitChoosing the best JavaScript framework/library/toolkit
Choosing the best JavaScript framework/library/toolkit
Hristo Chakarov
 
Armadura oxidada robert fish
Armadura oxidada  robert fishArmadura oxidada  robert fish
Armadura oxidada robert fish
Vero Ponce
 
Dispositivos electronicos michael perez (2)
Dispositivos electronicos michael perez (2)Dispositivos electronicos michael perez (2)
Dispositivos electronicos michael perez (2)
michael_10
 

Destacado (18)

Caleb bucket list
Caleb bucket listCaleb bucket list
Caleb bucket list
 
Megan's Bucket List
Megan's Bucket ListMegan's Bucket List
Megan's Bucket List
 
Cross-platform JavaScript
Cross-platform JavaScriptCross-platform JavaScript
Cross-platform JavaScript
 
Choosing the best JavaScript framework/library/toolkit
Choosing the best JavaScript framework/library/toolkitChoosing the best JavaScript framework/library/toolkit
Choosing the best JavaScript framework/library/toolkit
 
Caleb bucket list
Caleb bucket listCaleb bucket list
Caleb bucket list
 
Choosing the right JavaScript library/framework/toolkit for our project
Choosing the right JavaScript library/framework/toolkit for our projectChoosing the right JavaScript library/framework/toolkit for our project
Choosing the right JavaScript library/framework/toolkit for our project
 
Armadura oxidada robert fish
Armadura oxidada  robert fishArmadura oxidada  robert fish
Armadura oxidada robert fish
 
Dispositivos electronicos michael perez (2)
Dispositivos electronicos michael perez (2)Dispositivos electronicos michael perez (2)
Dispositivos electronicos michael perez (2)
 
Tổng quan về số tự nhiên
Tổng quan về số tự nhiênTổng quan về số tự nhiên
Tổng quan về số tự nhiên
 
WP-Boot
WP-BootWP-Boot
WP-Boot
 
Tính Tổng Với Các Số Hạng Là Phân Số
Tính Tổng Với Các Số Hạng Là Phân SốTính Tổng Với Các Số Hạng Là Phân Số
Tính Tổng Với Các Số Hạng Là Phân Số
 
Hướng dẫn phụ huynh chương trình giảng dạy lớp 5
Hướng dẫn phụ huynh chương trình giảng dạy lớp 5Hướng dẫn phụ huynh chương trình giảng dạy lớp 5
Hướng dẫn phụ huynh chương trình giảng dạy lớp 5
 
Chứng minh hai đoạn thẳng bằng nhau
Chứng minh hai đoạn thẳng bằng nhauChứng minh hai đoạn thẳng bằng nhau
Chứng minh hai đoạn thẳng bằng nhau
 
Một Số Kỹ Năng Giải Hệ Luyện Thi Đại Học
Một Số Kỹ Năng Giải Hệ Luyện Thi Đại HọcMột Số Kỹ Năng Giải Hệ Luyện Thi Đại Học
Một Số Kỹ Năng Giải Hệ Luyện Thi Đại Học
 
1440cauhoiluyenthiquocgiatbkhap1daodongco
1440cauhoiluyenthiquocgiatbkhap1daodongco1440cauhoiluyenthiquocgiatbkhap1daodongco
1440cauhoiluyenthiquocgiatbkhap1daodongco
 
Sử dụng quan hệ giữa đường vuông góc , đường xiên , hình chiếu. Để giải các b...
Sử dụng quan hệ giữa đường vuông góc , đường xiên , hình chiếu. Để giải các b...Sử dụng quan hệ giữa đường vuông góc , đường xiên , hình chiếu. Để giải các b...
Sử dụng quan hệ giữa đường vuông góc , đường xiên , hình chiếu. Để giải các b...
 
Bài Luyện Tập Về Phân Số Lớp 5
Bài Luyện Tập Về Phân Số Lớp 5Bài Luyện Tập Về Phân Số Lớp 5
Bài Luyện Tập Về Phân Số Lớp 5
 
Dang 3: Chứng minh ba điểm thẳng hàng
Dang 3: Chứng minh ba điểm thẳng hàngDang 3: Chứng minh ba điểm thẳng hàng
Dang 3: Chứng minh ba điểm thẳng hàng
 

Similar a DOM Performance (JSNext Bulgaria)

#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
Justin Cataldo
 
OpenNebulaConf 2014 - Puppet and OpenNebula - David Lutterkort
OpenNebulaConf 2014 - Puppet and OpenNebula - David LutterkortOpenNebulaConf 2014 - Puppet and OpenNebula - David Lutterkort
OpenNebulaConf 2014 - Puppet and OpenNebula - David Lutterkort
OpenNebula Project
 
Using Puppet - Real World Configuration Management
Using Puppet - Real World Configuration ManagementUsing Puppet - Real World Configuration Management
Using Puppet - Real World Configuration Management
James Turnbull
 

Similar a DOM Performance (JSNext Bulgaria) (20)

Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQuery
 
Modern JavaScript Programming
Modern JavaScript Programming Modern JavaScript Programming
Modern JavaScript Programming
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
OpenNebulaConf 2014 - Puppet and OpenNebula - David Lutterkort
OpenNebulaConf 2014 - Puppet and OpenNebula - David LutterkortOpenNebulaConf 2014 - Puppet and OpenNebula - David Lutterkort
OpenNebulaConf 2014 - Puppet and OpenNebula - David Lutterkort
 
OpenNebula Conf 2014 | Puppet and OpenNebula - David Lutterkort
OpenNebula Conf 2014 | Puppet and OpenNebula - David LutterkortOpenNebula Conf 2014 | Puppet and OpenNebula - David Lutterkort
OpenNebula Conf 2014 | Puppet and OpenNebula - David Lutterkort
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
5 x HTML5 worth using in APEX (5)
5 x HTML5 worth using in APEX (5)5 x HTML5 worth using in APEX (5)
5 x HTML5 worth using in APEX (5)
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationLotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
 
WP - Unit I.ppt
WP - Unit I.pptWP - Unit I.ppt
WP - Unit I.ppt
 
Catalyst MVC
Catalyst MVCCatalyst MVC
Catalyst MVC
 
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
 
CQRS / ES & DDD Demystified
CQRS / ES & DDD DemystifiedCQRS / ES & DDD Demystified
CQRS / ES & DDD Demystified
 
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
 
The Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQueryThe Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQuery
 
Using Puppet - Real World Configuration Management
Using Puppet - Real World Configuration ManagementUsing Puppet - Real World Configuration Management
Using Puppet - Real World Configuration Management
 
NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05
 
NodeJS in Windows Azure
NodeJS in Windows AzureNodeJS in Windows Azure
NodeJS in Windows Azure
 
Devoxx france 2015 influxdb
Devoxx france 2015 influxdbDevoxx france 2015 influxdb
Devoxx france 2015 influxdb
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Último (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

DOM Performance (JSNext Bulgaria)

  • 1. var title = “DOM Performance”; Nov 23, 2014 Nov 23, 2014 Sofia var info = { name: “Hristo Chakarov”, otherOptional: undefined };
  • 2. Nov 23, 2014 agenda(); • Why performance is so important • Event delegation • Stylesheet manipulation • DOM creation • DOM destruction • Questions
  • 3. Nov 23, 2014 Performance Why so important?
  • 5. Nov 23, 2014 Why performance matters? Good performance improves User Experience (UX) • Slow performance is very obvious • Users don’t enjoy waiting
  • 7. Nov 23, 2014 DOM operations are heavy • createElement is most expensive • The more elements you need to operate with, the worse performance you get o Event handling o Styling
  • 8. Nov 23, 2014 Event Delegation What is it & how it affects performance
  • 10. Handling events on a single element Nov 23, 2014 var cell = document.querySelector('td'); cell.addEventListener( 'click', function ( event ) { // mark the cell in blue this.style.background = 'blue'; });
  • 11. Handling events on multiple elements Nov 23, 2014 // imagine that we have 30’000 or more <td> elements… var cells = document.querySelectorAll('td'); // create single event handler var handler = function ( event ) { // mark the cell in blue this.style.background = 'blue'; }; for ( var i=0, l=cells.length; i<l; i += 1 ) { // add listener to every single cell... cells[i].addEventListener( 'click', handler ); }
  • 12. Nov 23, 2014 Delegate?
  • 13. Nov 23, 2014 Event delegation Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent.
  • 14. Nov 23, 2014 Delegate event // delegate click event to the table var table = document.querySelector('table'); table.addEventListener( 'click', function ( event ) { // `this` is the whole <table>, but `event.target` is the cell that has been clicked event.target.style.background = 'blue'; });
  • 15. Nov 23, 2014 Delegate event // delegate click event to the table var table = document.querySelector('table'); table.addEventListener( 'click', function ( event ) { // `this` is the whole <table>, but `event.target` //is the element that has been clicked // find out the <td> element var cell = event.target; while ( cell && cell.tagName != 'TD' && cell != this ) { cell = cell.parentNode; } cell.style.background = 'blue'; });
  • 16. Event delegation performance results Nov 23, 2014 http://jsperf.com/delegate-event
  • 17. Event delegation - pros & cons • Drastically increases performance • It’s alive! Elements about to be appended later automagically delegate the event to the parent • Not suitable for some kinds of events Nov 23, 2014 o mouseenter/mouseleave o mouseover/mouseout
  • 18. Nov 23, 2014 Styling How can we style thousands of elements without reducing the performance?
  • 20. Nov 23, 2014 Styling elements document.querySelector('tr').style.height = '75px'; // what if we have 100’000 rows? [].slice.call( document.querySelectorAll('tr') ).forEach( function ( tr ) { tr.style.height = '75px'; });
  • 22. Nov 23, 2014 Using a style sheet document.head.appendChild( document.createElement('style') ).innerHTML = 'tr { height: 75px }';
  • 23. Nov 23, 2014 Stylesheet API // get the styleSheet object var sheet = document.querySelector('style').sheet; // insert new CSS rule at the bottom of the stylesheet sheet.insertRule( 'tr { height: 75px }', sheet.cssRules.length ); // delete the top CSS rule sheet.deleteRule( 0 );
  • 24. Still supporting IE8? No problem! https://github.com/ickata/utilities/blob/ master/JavaScript/Source/stylesheet-api.js Nov 23, 2014
  • 25. Nov 23, 2014 Styling performance results http://jsperf.com/stylesheet-api
  • 26. Nov 23, 2014 Stylesheet API - pros & cons • Drastically increases performance • It’s alive! Elements about to be appended later automagically inherit styles • Not cross-browser o insertRule/addRule o deleteRule/removeRule o cssRules/rules o innerHTML/styleSheet.cssText
  • 27. Nov 23, 2014 DOM creation Interactive SPA requires a lot of new DOM elements
  • 28. createElement vs cloneNode vs innerHTML • createElement is the slowest DOM operation • cloning a single node or a structure via cloneNode is much faster • old-school innerHTML is much faster as well Nov 23, 2014 o innerHTML is not approved by W3, but all browsers support it
  • 29. DOM creation performance results Nov 23, 2014 http://jsperf.com/dom-creation-4
  • 31. Can we get even better results? Nov 23, 2014
  • 32. Nov 23, 2014 DocumentFragment DocumentFragment is a lightweight container that can hold DOM nodes. Various operations, such as inserting nodes as children of another Node, may take DocumentFragment objects as arguments; this results in all the child nodes of the DocumentFragment being moved to the child list of this node.
  • 33. Nov 23, 2014 Clone a DocumentFragment If we append 10 elements to a DocumentFragment, and then append to the same fragment a clone of it, as a result the fragment will contain 20 elements. If we repeat the fragment clone/append operations 2 more times - we will get a fragment with a total of 80 elements!
  • 34. Cloning fragments dramatically reduces the # of operations! Nov 23, 2014
  • 35. Nov 23, 2014 Clone fragments algorithm • Create desired number of elements using DocumentFragment & cloneNode • Use less operations as possible
  • 36. Nov 23, 2014 Clone fragments algorithm • Reduce the total # of desired elements by division of 2 until we get odd number or the simple numbers 2 or 3 • Subtract 1 from odd numbers & continue division by 2 unless result is 2 or 3. Store the step index for later (when we will have to add +1)
  • 37. Nov 23, 2014 Clone fragments algorithm • Create 2 or 3 clones of the source element • Multiply by 2 until we reach the desired number of cloned elements • Add +1 to the result on each stored step
  • 38. Clone fragments algorithm example 1000 = ((((3 * 2 + 1) * 2 + 1) * 2 + 1) * 2 * 2 + 1) * 2 * 2 * 2 Nov 23, 2014
  • 39. Nov 23, 2014 cloneMultiple https://github.com/ickata/utilities/blob/ master/JavaScript/Source/element-clone-multiple. js
  • 40. Nov 23, 2014 cloneNode vs cloneMultiple
  • 41. cloneNode vs cloneMultiple - Chrome Nov 23, 2014
  • 42. cloneNode vs cloneMultiple - Firefox Nov 23, 2014
  • 43. cloneNode vs cloneMultiple - IE8 Nov 23, 2014
  • 44. Nov 23, 2014 cloneMultiple - summary • Makes sense to use for large amount of elements • Reduces # of DOM operations to clone elements • The more elements we clone, the less # of operations we have! o to clone 1000 elements, we need only 33 operations! o to clone 2000 - we need only 35!
  • 46. Nov 23, 2014 DOM destruction
  • 47. Nov 23, 2014 Destroying elements // remove a single element parentNode.removeChild( element ); // remove all descendants parentNode.innerHTML = ""; // wow.. that’s heavy
  • 48. Nov 23, 2014 Destroying elements • innerHTML destroys all elements one by one • removeChild destroys the element with all its descendants • design your system in a way so when you need to remove multiple elements you remove their parent o that’s a single operation!
  • 49. Nov 23, 2014 Resources
  • 50. Nov 23, 2014 Resources • DocumentFragment • Performance Tests o Event Delegation o Stylesheet Manipulation o DOM Creation • DOM Performance (BG)
  • 52. Nov 23, 2014 Questions?
  • 53. Nov 23, 2014 Upcoming events ISTA Conference 26-27 November http://istabg.org/ Stay tuned for 2015: Azure Bootcamp http://azure-camp. eu/ UXify Bulgaria http://uxify.org/ SQLSaturday https:// www.sqlsaturday.com/ and more js.next();
  • 54. Nov 23, 2014 Thanks to our Sponsors: Diamond Sponsor: Hosting partner: Gold Sponsors: Silver Sponsors: Technological Partners: Bronze Sponsors: Swag Sponsors: Media Partners:
  • 55. Nov 23, 2014 Thanks for listening! • Hristo Chakarov • Front-end architect • SiteKreator • JavaScript trainer • IT Academy • Photographer • @github • +HristoChakarov