High Performance JS & CSS


http://bit.ly/1gx0FRU


MD Khan / @mdkhan005

http://bit.ly/1gx0FRU

Quick Performance!

How do we develop a app?

Performance matters ! ! ! !

Every milisecond counts

Optimization :-

  • Subjective
  • Could be Expensive
  • Not Always Valid
  • Don't Guess, Measure it

Expectations !!!

  • Browser
  • CSS
  • JavaScript
  • Debug

How Browser Works??

Browser

  • Versions
  • Bugs
  • Changing

Why learn about Browser?


  • Play Ground
  • Geek / Freak
  • Don't forget Devices
W3.org: navigation-timing

Your Html


1.  <html>
2.      <body>
3.         <p>
4.            Hello World
5.        </p>
6.        <div> 
7.           <img src="example.png"/>
8.        </div>
9.     </body>
10. </html>

						
How Browser Works

Validate Html


Don’t Just Wrap a DIV Around It


Make HTML Parsing Easier



30 CSS Best Practices

Style


p,div{
  margin-top:3px;
}

.error {
  color:red;
}
						

Render Tree

So far

Layout

CSS Layout Engines

Paint

Need to Change

Avoid Change

  • Minimum change
  • Don't change Layout
  • Change Background Color
  • Change Text Color
  • Visibility: hidden

Re paint

More Changes => More Work

  • Change Layout
  • Change Width / Height
  • Change Font
  • Move DOM Node
  • Resize Window
  • Display: none

Re Flow

Try to Avoid

Re-flow

Use DOM DocumentFragment

Clone the DOM


Styles affect paint and layout
John Resig: DOM DocumentFragment
MDN: DocumentFragment
Re flow Layout
JS best practices
Nicholas Zakas: 10 JS Performance Boosting

Lets Talk about CSS

CSS Selectors

ID


1. <style>
2.  #myFirstTODO
3.  {
4.     color:red;
5.  }
6.  </style>
7.
8.  <div>
9.      <p id="myFirstTODO"> have to shower </p>
10.     <p> have to shave</p>
11.     <p> have to cut hair</p>
12.     <p> buy perfume</p>
13.     <p> at least buy t shirt</p>
14. </div>
							

Class


1. <style>
2.  .greenBold
3.  {
4.     color: green;
5.     font-weight:bold;
6.  }
7.  </style>
8.
9.  <div>
10.     <p> have to shower</p>
11.     <p class="greenBold"> have to shave</p>
12.     <p class="greenBold"> have to cut hair</p>
13.     <p> buy perfume</p>
14.     <p> at least buy t shirt</p>
15. </div>
							

Immediate Children


1. <style>
2.  li > ul
3.  {
4.     color: green;
5.     font-weight: bold;
6.  }
7.  </style>
8.
9.  <div>  
10.     <ul>  
11.         <li> List Item  
12.            <ul>  
13.                <li> Child </li>  
14.            </ul>  
15.         </li>  
16.         <li> List Item </li>  
17.         <li> List Item </li>  
18.         <li> List Item </li>  
19.    </ul>  
20. </div> 						

Descendent


#myTODO p
  {
     color: green;
     font-weight: bold;
  }
							

Fancy Selectors



div + p { /*Adjacent*/ }

div ~ p { /*Sibling*/ }

input[type="checkbox"] { /*Attribute*/}

p:first-child { /*pseudo*/}



Advanced CSS Selectors

You can

Doesn't mean you should



Better Quality CSS
Best Practices are killing us
CSS Optimization

Render Speed


ID - #myID


Class – .myClass


Tag – div


Sibling – div + p, div ~ p


Child – div > p



Descendant – div p


Universal – div *


Attribute – input[type="checkbox"]


Pseudo – p:first-child



Efficient CSS Selector
Faster HTML and CSS

This doesn't mean everything should be ID


ID and Class: Almost Similar


DRY, Readable & Maintainable


Fast


Difference between ID and Class

CSS Try to Avoid



Rendering Best practices
Google: Optimize Browser Rendering

Universal Key Selector


body * {
	color:#365277;
}

.hide-scrollbars * {
	font-size: 16px;
}								
							

When you can't read easily. Same to Browser


#myDiv ul li button 
{ 
   width:200px;
}

#myDiv ul li:nth-child(2) li:nth-child(7) > a 
{
   color:red;
}
								

Use class


.btnMedium 
{
   width:200px;
}

.myClass 
{
   color:red;
}
								

Don't Repeat


.upTrend
{
    background-image:url('upGreen.jpg');
    background-repeat:no-repeat;
    background-position: center center;
    padding-left:20px;          
}

.downTrend
{
    background-image:url('downRed.jpg');
    background-repeat:no-repeat;
    background-position: center center;
    padding-left:20px;
}
								

Still Repeating


.upTrend
{
    background-image:url('upGreen.jpg') center center no-repeat;
    padding-left:20px;          
}

.downTrend
{
    background-image:url('downRed.jpg') center center no-repeat;    
    padding-left:20px;
}
								

Combine Common Styles


.upTrend
{
    background-image:url('upGreen.jpg');            
}

.downTrend
{
    background-image:url('downRed.jpg');            
}

.upTrend, .downTrend 
{
    background-repeat:no-repeat;
    background-position: center center;
    padding-left:20px;
}
								
DRYer CSS

Be as specific as possible.


ul li a 
{
  /* My awesome anchor */
}

* html #atticPromo ul li a 
{
  /* My awesome rules */
}
								

Redundant selectors


ul #top_blue_nav 
{
  ...
}

form #UserLogin 
{
  ...
}
								

Check again your child selectors



//don't
treeitem[IsImapServer="true"] > treerow > .tree-folderpane-icon 
{
   ... 
}


//do
.tree-folderpane-icon[IsImapServer="true"] 
{
   ...
}

								

Mozilla Rendering Guides

How CSS Selectors are Matched


1. <html>
2.  <head>
3.    //head omitted due to lack of brain
4.  </head>
5.  <body>
6.    <header>
7.      <h1>My Awesome title</h1>
8.    </header>
9.    <nav>
10.      <ol>
11.        <li><a href="#">StackOverflow</a></li>
12.        <li><a href="#">StackOverflow</a></li>
13.      </ol>
14.    </nav>
15.    <section>
16.      <div>
17.        <ul>
18.          <li><a href="#">StackOverflow</a></li>
19.          <li><a href="#">StackOverflow</a></li>
20.        </ul>
21.      </div>
22.    </section>
23.  </body>
24.</html>
								

li { color: red; }

  • Run only once

nav a {color:green;}

nav a {color:green;}

nav a {color:green;}

nav a {color:green;}

Browser Evaluates Selectors?

Right to Left

<=





CSS hierarchy matching
High Performance CSS
CSS Code Design

CSS Specificity





/* Take Advantage of CSS specificity  */
/* class, id, inline, !important */

							

Estelle Weyl: CSS SpeciFISHity
CSS-Tricks: CSS Specificity
Understanding CSS
MDN: Specificity
Specificity calculator
Power of Specificity
CSS Specificity: Things you should know

Unused CSS

Detect Unused Css

JavaScript

JS try to Avoid

Access Same Variable


var blah = document.getElementById('myID');
var blah2 = document.getElementById('myID2');
var blah3 = document.getElementById('myID3');


var blah = document.getElementById('myID'),
    blah2 = document.getElementById('myID2'),
    blah3 = document.getElementById('myID3');
							

Localize variable


var doc = document,
    blah = doc.getElementById('myID'),
    blah2 = doc.getElementById('myID2'),
    blah3 = doc.getElementById('myID3');

							

My For Loop


for(var i = 0; i < someArray.length; i++) {  
   
   var container = document.getElementById('container');  
   container.innerHtml += 'my number: ' + i;  
   console.log(i);  
} 

							

Cache outside of loop



var container = document.getElementById('container');  

for(var i = 0; i < someArray.length; i++) {     
   
   container.innerHtml += 'my number: ' + i;  
   console.log(i);  
} 

							

Little More!!!


var container = document.getElementById('container');  

for(var i = 0, len = someArray.length; i < len; i++) {     
   
   container.innerHtml += 'my number: ' + i;  
   console.log(i);  
} 
							

Even Better


var i,
  length = 100;

for ( i = 0; i < length; i++ ) {
  // statements
}

// Or...
var i = 0,
  length = 100;

for ( ; i < length; i++ ) {
  // statements
}
							
Idiomatic JS

Use === than ==


0 == ''; // true
0 === false; //false
							

if (( x === null) || (x === undefined)){ ... }

if(x == null) { ... }
							

When you don't actually know whether they are same type


typeof thing == 'function'; //always be string
myArray.length == 0;  //will always be number
mySting.indexOf('x') == 0;
							
bReaK aLL thE RuleZ

Initialize if Undefined


if ( !MyNamespace ) {
  var MyNamespace = { };
}

//or
var myNamespace = myNamespace || {};

//or http://jsperf.com/conditional-assignment
// myNamespace || ( myNamespace = {} );


//or
if ( typeof MyNamespace == ’undefined’ ) {
  var MyNamespace = { };
}
							
Nokia: JS Best Practice

JavaScript: String

String Concatenation


var tinyMessage = 'Trust me, i started one line' + 
		  'Designer told me he wants little more' + 
		  'I added little more' +
		  'Manager said, this is not enough' +
		  "He didn't said what to add" +
		  'Just said add' +
		  "I didn't know what to add" +
		  'So i added a slice of pizza' +
		  'Client said this is stupid' +
		  'Manager said, client is right';
							
Optimize JavaScript

[ ].join(' ')


var tinyMessage = ['Trust me, i started one line', 
		   'Designer told me he wants little more', 
		   'I added little more',
		   'Manager said, this is not enough',
		   "He didn't said what to add",
		   'Just said add',
		   "I didn't know what to add",
		   'So i added a slice of pizza',
		   'Client said this is stupid',
		   'Manager said, client is right'].join(' ');
							
array-join-vs-string-connect
Why is string concatenation faster than array join
fastest-way-to-build-this-string

Your Own String Builder


var strBuilder = ['First 20 fibonacci numbers:'];

for (var i = 0; i < 20; i++) {
  strBuilder.push( i, '=', fibonacci(i));
}

var fibonacciStr = strBuilder.join(' ');
							

Object Vs Array

Array

Same Type

Use Full Array

Avoid Pre-allocate

Grow as you Go


Type Inference Performance
Sparse vs Full Arrays
Pre-allocated Arrays


// Don't do this:
a = []; // executor knows nothing
for(var i = 1; i <= 4; i++) {
	 a.push(i);
}

// just do it:
var a = [1, 2, 3, 4];
							

Delete is not delete


var myArray = [1, 2, 3, 4, 5, 6]; //myArray.length = 6

delete myArray[2]; 

myArray; //[1, 2, undefined × 1, 4, 5,6]
console.log(myArray.length); // 6
console.log(myArray[2]); // undefined 

							

Array.splice


myArray.splice(2,1);
							

Objects


Varying types properties


Integer-indexed Objects is always faster


Use Object.Create()


Object.create() vs. constructor vs. object literal

Delete is not delete


var o = { x: 1 }; 
delete o.x; // true 
o.x; // undefined
							

Let GC Breathe

Holding references


function getLargeThing (x) {
  var a = function () {
    var largeStr = new Array(1000000).join('x');
	return function () {
		return largeStr;
	};
}();
							
Fast Memory Efficient JavaScript
JSPerf: Closure vs Shared method

Trust Arguments


if (callback && typeof callback === "function"){
	/* rest of your logic */
}else{
	/* not a valid function */
}

							
JavaScript Code Review

Momoization

Memoization


var fibonacci = function (n) {
   return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
};
for (var i = 0; i <= 10; i += 1) {
   console.log( i + ': ' + fibonacci(i));
}

// 0: 0
// 1: 1
// 2: 1
// 3: 2
// 4: 3
// 5: 5
// 6: 8
// 7: 13
// 8: 21
// 9: 34
// 10: 55
							

JavaScript: Good Parts


var fibonacci = (function () {
  var memo = [0, 1];
  var fib = function (n) {
     var result = memo[n];
     if (typeof result !== 'number') {
         result = fib(n - 1) + fib(n - 2);
         memo[n] = result;
     }
     return result;
  };
  return fib;
})();
							

General Memoization


Function.prototype.memoize = function(){
    var self = this, cache = {};
    return function( arg ){
      if(arg in cache) {
        console.log('Cache hit for '+arg);
        return cache[arg];
      } else {
        console.log('Cache miss for '+arg);
        return cache[arg] = self( arg );
      }
    }
  }
							
Addy Osmani: Faster JS Memoization

Implement general Memoize



function fooBar(a){ ... }
// once a memoizer is available, usage is as simple as
var memoFooBar = fooBar.memoize();
memoFooBar(1);
// are conducted. This result is then cached for next time.
memoFooBar(1); // will now return the cached result
memoFooBar(2); // whilst this will need to be calculated
							
Addy Osmani: Optimized Memoization Library

JavaScript Others

Reduce Global


var current = null;
function init(){...}
function change(){...}
function verify(){...}
							

var myNameSpace = {
  current:null,
  init:function(){...},
  change:function(){...},
  verify:function(){...}
}

myNameSpace.init();

							
W3.org JS best practice
Develop with Namespace
JS 24 best practices

Self executing


(function(){
  var current = null;
  function init(){...}
  function change(){...}
  function verify(){...}
})();							
							

(function( skillet, $, undefined ) {
    //Private Property
    var amountOfGrease = "1 Cup";

    //Public Method
    skillet.toString = function() {
        console.log( skillet.quantity + " " + 
                     skillet.ingredient + " & " + 
                     amountOfGrease + " of Grease" );
        console.log( isHot ? "Hot" : "Cold" );
    };    
}( window.skillet = window.skillet || {}, jQuery ));								
							

Re-think try-catch

Rethink: Try-catch
JSPerf: try-catch vs if check
JS: try catch vs Error checking
Why Empty catch block is bad

Use Strict Mode


// Non-strict code...
 
(function(){
  "use strict";
 
  // Define your library strictly...
})();
 
// Non-strict code...
							
John Resig: Strict Mode

DOM vs innerHTML

Templating JS vs Mustache

JSPerf: Dom vs innerhtml based templating
Mustache Manual

Know Javascript Engine

  • Know V8
  • Hidden Class
  • Avoid Memory Leaks
  • Compile browser

Memory Efficient JS

JQuery

Don't use it for 3 lines of Code


$(document).ready(function () {
   alert('document is ready. I can sleep now');            
});
							

Script as Last Tag of body

Self Executing function


document.onreadystatechange = function () {
  //docuemnt ready. dont work for older browser or IE
  if (document.readyState == "complete") {
      alert('document is ready. I can sleep now');
  }
}							

Copy ready: function from JQuery

5-things-you-should-stop-doing-with-jquery

Selector Repetition


$('#myText').css("color", "blue");
$('#myText').css("font-size", "1.2em");
$('#myText').text("Text changed!");	
							

//chain it or cache it

$('#myText').css({ "color": "blue", "font-size": "1.2em"}).text("Text changed!");
							

//better
.myClass{
	color:blue;
	font-size:1.2em;
}
//apply class not style
$('#myText').addClass('myClass').text("Text changed!");
							

Efficient JQuery Selector

Use Sub queries


<ul class="nav">
  <li>List 1, item 1</li>
  <li>List 1, item 2</li>
  <li>List 1, item 3</li>
</ul>
<ul class="nav">
  <li>List 2, item 1</li>
  <li>List 2, item 2</li>
  <li>List 2, item 3</li>
</ul>
							

$( "ul.nav li:eq(1)" ).css( "backgroundColor", "#ff0" );
//better								
$( "ul.nav" ).each(function( index ) {
  $( this ).find( "li:eq(1)" ).css( "backgroundColor", "#ff0" );
});
							

Remember :=> JQuery is not Database

jquery-performance-rules
15-powerful-jquery-tips-and-tricks

Jquery Also !

Right to left




Jquery Right to left
Your jQuery: Now With 67% Less Suck
JSPerf: Jquery Right to Left
Why Right to Left

High Performance Network

Small is Big

Every byte counts

Every byte will bite!

Minify

ggl closure (demo)
JS Compress
Uglify
JS Min

CSS Tidy
Minify CSS
CSS Minifier

Combine

CommonJS, Require JS

Give the load to Grunt!

Yo

http://yeoman.io

Order Matters

Style on Top

Script on bottom


Cuzillion demo (youtube)

Properly include style and scripts

Async Vs Defer

Dont block


<script src="file-a.js"></script>
<script src="file-b.js" defer></script>
<script src="file-c.js" async></script>
							

Async Vs Defer

Small in line

Other than loding different file

Good for Mobile device

gZip

7-zip

Jank

jank layers hover scroll
Jank Invaders
Debugging and Fixing Jank
Jank Free

Scroll could be scary!



Scrolling Performance
unnecessary Paints

Something else make Scroll bad!

  • position:fixed
  • overflow:scroll
  • :hover effect
  • touch listeners
  • Image resize
slow scroll with fixed position Jank-busters

requestAnimationFrame (rAF)

Browser dynamically adjust to keep frame rate normal.

Parallax


window.onscroll = function(e) { 
  var parallax = document.getElementById('parallax-background'); 
  parallax.style.marginTop = (window.scrollY/2) + 'px';
 
}								
							

window.onscroll = function(e) {
 
  // could use prefixes: webkitTransform, mozTransform etc.
 
  var parallax = document.getElementById('parallax-background');
 
  parallax.style.transform = 'translate3d(0px,' + (window.scrollY/2) + 'px, 0px)';
 
}								
							
Flickr: Parallax

Debounce & Throttle

Defer


Debounce: Example

Performance Debug

JS Profiling
Profiles
Performance Secret: Peter Flynn

Console API


//test
console.assert(myArray.length >5, "More than 5 elements");

//hit count
console.count("Number of times entered");

//JS represents of Obj
console.dir(document.body);

//trace
console.trace();
							
Using the console
Console API

More Console


console.time("Array initialize");

var array= new Array(1000000);

for (var i = array.length - 1; i >= 0; i--) {
    array[i] = new Object();
};

console.timeEnd("Array initialize");
							

Performance Debug


var start = performance.now();

//execute your function
foobar();

var end = performance.now();

console.log(start - end +'ms');
							
Axel Rauschmayer: JS Console API CodeSchool: Discover Dev Tools

Rectangle

Settings

Memory Profiling

JS Memory Profiling
Long paint times profiling
Effective Memory management
Leak Finder

chrome://tracing

Tracing paint operations
Tracing Flag

Break Everything


I have said

\

/

As Long As YOU know what YOU ARE doing




Break All the Rules

Review Your Code

JSMentors
Code Review

Fun with JavaScript

Together JS

Mozilla Together JS

WAT!

Gary Bernhardth CodeMash 2012

JS Wizardy

Martin Kleppe: JS Conf EU

promise().then()

JavaScipt Ninja
UnderScore or JQuery source code
High Performance Browser Network
asm.js: JS compile Target
Lo-dash

Take Away

  • Nothing is absolutely right

trust Tools, not Rules


Angus Croll: Break all the rules

Free Tip

Thank You


http://bit.ly/1gx0FRU



MD Khan / @mdkhan005
http://bit.ly/1gx0FRU
http://bit.ly/1gx0FRU