Optimizing JavaScript
-
Converting numbers: always use
parseInt(num, 10)Convert
"16"to number: http://jsperf.com/number-vs-parseint-vs-plus/26Convert
"16px"to number: http://jsperf.com/number-vs-parseint-vs-plus/25 -
Cascading configuration options: use
prototyperather than$.extendThis technique cannot be applied everywhere, but is a great candidate for Handsontable cascading settings pattern (Constructor
options->columns->cells->cellProperties).See more: http://jsperf.com/extending-settings
-
Custom functions can be faster than native (for example
forEach)According to tests ran at JSPerf, MDN shim of
forEachcan be up to 5 times faster than the native implementation. -
forEachandfilterare MUCH slower thanforforcan be 10 times faster than aforEach.See more: http://jsperf.com/for-vs-foreach/49
-
callis faster thanapplySee more: http://jsperf.com/function-calls-direct-vs-apply-vs-call-vs-bind/33
Optimizing DOM
-
Emptying nodes: always prefer
removeNode()overinnerHTML = ''See more: http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9
-
Search for ID or by tag: prefer
getElementByIdorgetElementsByTagName -
Get first element using DOM (
getElementsByTagName('span')[0]orfirstChild) -
Create text elements:
createTextNodecan be many times faster thaninnerHTML -
Check if element has child nodes:
if (DIV.firstChild)
See more: http://jsperf.com/id-vs-getelementbyid/3
See more: http://jsperf.com/jquery-first-vs-first2/10
See more: http://jsperf.com/creating-text-node/3
See more: http://jsperf.com/empty-node-if-needed
Optimizing CSS
-
Change style by caching
var style = element.style