Recently, I’ve discovered some simple tricks to get my Javascript code to execute faster.
This is not a full list, just some that I use fairly often. If anyone has others, please post them in the comments. It would be great to compile a large list.
Before I begin, I would like to emphasize a phrase that every developer should know. “Premature optimization is the root all evil.” Optimization can only get you so far. Good programming practices and code structure are more important. With that, let’s get started.
Use for loops instead of Array.forEach, for.. in, jQuery.each etc.
var arr = Array(10000).join(‘x’).split(‘’);
for (var i = 0, len = arr.length; i < len; i++) {
..some code on the array
}
instead of
arr.forEach(function (item, i) {
..some code on the array
});
or
for (var i in arr) {
if(arr.hasOwnProperty(i)) {
..some code on the array
}
}
In general, a for loop will execute 10x faster than Array.forEach or for..in. Here is the JSPerf comparison
Don’t create functions in loops or commonly used code
Each function carries memory overhead. Define functions that are commonly used. Only use anonymous function when necessary.
for( var i = 0; i < 100; i++) {
setTimeout(function() {
.. do something
}, 10);
}
instead do this
function repeatedFn() {
.. do something
}
for( var i = 0; i < 100; i++) {
setTimeout(repeatedFn, 10);
}
Avoid unnecessary functions calls / closures
Even if you aren’t using anonymous functions. All functions still have overhead. Don’t create unnecessary functions.
For instance, don’t make an add function
function add(a, b) {
return a + b;
}
Check out this JSPerf comparison
Use vanilla javascript when possible
Libraries/Frameworks can be great for code organization, cross-browser compatibility, etc. Vanilla javascript is much faster in certain circumstances. For instance, I often see people use jQuery to call the click handler on a DOM element.
$testDiv.trigger(‘click’) or $testDiv.triggerHandler(‘click’);
the following is cleaner and significantly faster
onClickTest();
Check out this JSPerf comparison