make javascript faster

16
!Slow JS A Programmer is to a Coder, to what a Designer is to a Production Artist…

Upload: harish-verma

Post on 08-Jan-2017

25 views

Category:

Software


2 download

TRANSCRIPT

Page 1: Make JavaScript Faster

!Slow JSA Programmer is to a Coder, to what a Designer is to a Production Artist…

Page 2: Make JavaScript Faster

Advanced

Intermediate

Beginner

Target Audience

Page 3: Make JavaScript Faster

• Data structure Object vs Array

• Memory management Scope chain Data access De-referencing

• JS event loop Event loop setTimeout/setInterval

• Loops Faster loops

• UI rendering(jQuery) jQuery selectors Minimize reflow

• Chrome developer tool

Agenda

Page 4: Make JavaScript Faster

Object vs Array

// optimized, length=3, index lookupvar a= [10,20,30];

//sparse array, length = 9, output: [undefined × 4, 44, undefined × 3, 55]var b = []; b[4]= 44, b[8]=55;

//holed array, length=2, not goodvar c = [21,22,23]; c[1]= null; delete c[2];

visit code samples

Page 5: Make JavaScript Faster

Memory management Scope chain Data access Functions

Page 6: Make JavaScript Faster

Scope Chain

Golden rule: Further into the chain slower the resolutionThings to read; with, try/catch, clousure

Execution ContextScope

Scope Chain01

Activation Objectthis windowagruments [item]Item {array}div undefined

Globaldocument {object}window {object}

Page 7: Make JavaScript Faster

Data Access

I am faster

Literals or local variables > object property access

root.foo.name > root.foo.item.name

Page 8: Make JavaScript Faster

Functions

 avoids unnecessarily running the initialization code

Page 9: Make JavaScript Faster

JS Event Loop Event loop setTimeout/setInterval

Page 10: Make JavaScript Faster

Event Loop single thread == one task at a time Non-Preemption  Runtime contains a message queue. A

function is associated to each message. When the stack is empty, a message is taken

out of the queue and processed.

Page 11: Make JavaScript Faster

setTimeout/setInterval• Puts execution at the end of the event queue.• Timeout, in milliseconds, it will wait before

putting to queue.• Doesn’t guarantee to execute the function just

after the timeout passed.

Page 12: Make JavaScript Faster

Faster Loops• Reduce lookup• Control condition + control variable• Avoid for-in or for-each loop

Increase in perform

ance

Page 13: Make JavaScript Faster

UI Rendering(jQuery) jQuery selectors Minimize reflow

Page 14: Make JavaScript Faster

jQuery Selectors• Use IDs• Give context• Cache always

Page 15: Make JavaScript Faster

ReflowReflow is the process by which the geometry of the layout engine’s formatting objects are computed.

-Chris Waterson, MozillaDom manipulation is heavyDo DOM manipulations off the document.Change CSS, not styles

Page 16: Make JavaScript Faster

THANKS!!