Make JavaScript Faster
-
Upload
harish-verma -
Category
Software
-
view
25 -
download
2
Transcript of Make JavaScript Faster
!Slow JSA Programmer is to a Coder, to what a Designer is to a Production Artist…
Advanced
Intermediate
Beginner
Target Audience
• 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
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
Memory management Scope chain Data access Functions
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}
Data Access
I am faster
Literals or local variables > object property access
root.foo.name > root.foo.item.name
Functions
avoids unnecessarily running the initialization code
JS Event Loop Event loop setTimeout/setInterval
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.
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.
Faster Loops• Reduce lookup• Control condition + control variable• Avoid for-in or for-each loop
Increase in perform
ance
UI Rendering(jQuery) jQuery selectors Minimize reflow
jQuery Selectors• Use IDs• Give context• Cache always
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
THANKS!!