- When the return value of a function is needed multiple times, and the value is a constant, a variable should be used to cache it.
- In JavaScript, every dot that appears in a statement is equivalent to a function call.
- Run the following code and you should see a 20% to 50% performance increase, depending on the browser, when you avoid the dots.
var limit = 1000000;
var bigArray = new Array(limit);
// array.length
var start = (new Date()).getTime();
for (var i = 0; i < bigArray.length; i++) {
var x = Math.random();
}
document.write("array.length: " + ((new Date()).getTime() - start) + "<br/>");
// len = array.length
var start = (new Date()).getTime();
for (var i = 0, len = bigArray.length; i < len; i++) {
var x= Math.random();
}
document.write("len: " + ((new Date()).getTime() - start) + "<br/>");
//Math.floor
var start = (new Date()).getTime();
for (var i = 0; i < limit; i++) {
var x = Math.floor(Math.random());
}
document.write("Math.floor: " + ((new Date()).getTime() - start) + "<br/>");
// | 0
var start = (new Date()).getTime();
for (var i = 0; i < limit; i++) {
var x = Math.random() | 0; // floor.
}
document.write("| 0: " + ((new Date()).getTime() - start) + "<br/>");