1. Defining local variables
First, it goes through the local variables starting with this and then iterates through all global variables.
So, anytime, when you use a global variable more than once you can redefine it locally.
var name1 = document.getElementById(‘myID1’),
name2 = document.getElementById(‘myID2’);
var doc = document,
name1 = doc.getElementById(‘myID1’),
name2 = doc.getElementById(‘myID2’);
2. Avoiding with
Avoid using with in your code. Because with() appends an extra set of variables to the beginning of a scope chain and for performance, it has a negative impact, making it expensive for looking up variables in the other scopes.
Read Also: Tips and Tricks for powerful developers
3. Using closures
Creating a closure is comparing slower than creating an inner function, and much slower than reusing a static function.
4. Get rid of deeping into arrays
Don’t dig too deep into arrays. This cause the operation very slower. For e.g. if you dig three levels into an array then this is three array item lookup instead of one array.
5. Variables are always fast than objects and arrays
For optimizing issue, variables perform faster than object properties and array items. When you use an object property or array item for multiple times, you can get better performance by defining a variable.
6. Avoid browser memory leaks
7. Change CSS classes rather than styles
Changing CSS classes is more optimal than changing styles and this creates a re-flow issue. CSS classes don’t avoid re-flow and they simply minimize it. You can use a CSS class for changing a number of styles at once which in turn only incur a single re-flow.
8. Avoid touching the DOM
9. Initializing instance variables
Put instance variable declaration or initialization on a prototype for instance variables with value type initialization values. This can avoids unnecessarily running the initialization of a code each time while the constructor is calling.
10. Avoid for-in loops
Don’t use for-in loops. There is a very straightforward login behind this. Instead of looping through a set of indexes with a for or a do-while, a for-in loop not only through additional array items, but this is also requires more effort.
Use for each one. This comes with a slew of performance issues i.e. an extra function is introduced with a corresponding execution context which is created and destroyed.