Let's have an idea about JAVASCRIPT PERFORMANCE PATTERN, what is it? why do we need to use this? Etc.
Check out this presentation for all you need to know about javascript performance patterns.
2. TOPICS
1. What is PATTERN in this context?
2. Performance Pattern?
3. DOM manipulations.
4. ‘for’ loop optimization
5. Single threaded JS, performing async task.
4. PROGRAMMING PATTERNS
WIKIPEDIA:
In software engineering, a software design pattern is a general
reusable solution to a commonly occurring problem within a given
context in software design.
SIMPLY:
It’s a template/snippet of code, that can be reused to solve problems.
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
function Person(config) {
this.name = config.name;
this.age = config.age;
}
1
2
6. PERFORMANCE PATTERNS IN JS.
Why?
JS is single threaded, so, write fast synchronous codes,
because after all:
Blob fills Sea Blob
Code snippets that has lower runtime than the usual one.
Client side and server side (templating and REST APIs,
static stuffs)
7. DOM MANIPULATIONS
DOM manipulations are expensive, use CACHING
In JQuery, insert operations like prepend(), append(), after() are rather time-
consuming.
Example
var list = '';
for (var i=0; i<1000; i++) {
list += '<li>'+i+'</li>';
}
('#list').html (list);
for (var i=0; i<1000; i++) {
$(“#list").append(“<li>” +i+ “</li>”);
}
4
5
8. DOM CACHING
for (var i=0; i<1000; i++) {
$(“#list").append(“<li>” +i+ “</li>”);
}
5
But what if you have not any
option?
9. CACHING THE FREQUENTLY USED
OBJECTS.
Var list =$(“#list”)
for (var i=0; i<1000; i++) {
list.append(“<li>” +i+ “</li>”);
}
6
11. FOR LOOP
for (var i=0; i<items.length; i++)
{
// Magic
}
7
• The most common way to write a
loop, and without a doubt the
first way people learn how to do
it, is like this:
But where is the problem
exactly?
12. FOR LOOP OPTIMIZATION
for (var i=0; i<items.length; i++)
{
// Magic
}
8
for (var i=0; items[i]; i++) )
{
// Magic
}
9
for (var i=0, il=divs.length; i<il; i++)
{
// Magic
}
10
just compare the current iteration index to
the length saved in a variable.
for each iteration you need to do a look-up
of the array to see if an object exists at the
current index.
for each iteration in the loop, it needs to test
the current item and check the length of
array/collection you’re looping through.
13. PERFORMANCE OF ‘FOR’
for (var i=0; i<items.length; i++)
{
// Magic
}
8
for (var i=0; items[i]; i++) )
{
// Magic
}
9
for (var i=0, il=divs.length; i<il; i++)
{
// Magic
}
10
The test creates 10 000 div elements when
the page is loaded
29. CONTACT US
Do you have anything to build, let’s build together:
Contact Us: +91-9828247415
Visit our Website: www.habilelabs.io
mail us at: info@habilelabs.io