JS: Dots are bad, M’kay?


  • 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();

for (var i = 0; i < bigArray.length; i++) {

   var x = Math.random();

}

document.write(“array.length: “ + (+new Date() – start) + “<br/>”);

 

// len = array.length

var start = +new Date();

for (var i = 0, len = bigArray.length; i < len; i++) {

   var x= Math.random();

}

document.write(“len: “ + (+new Date() – start) + “<br/>”);

 

//Math.floor

var start = +new Date();

for (var i = 0; i < limit; i++) {

   var x = Math.floor(Math.random());

}

document.write(“Math.floor: “ + (+new Date() – start) + “<br/>”);

 

// | 0

var start = +new Date();

for (var i = 0; i < limit; i++) {

   var x = Math.random() | 0; // floor.

}

document.write(“| 0: “ + (+new Date() – start) + “<br/>”);

 

 

  • Also cache DOM elements such as “canvas.height” or even “document”.
  • Code that uses caching should result in 50% or much better performance:

// Without cache.

var start = +new Date();

 for (var i = 0; i < limit; i++) {

   var doc = document;

}

document.write(“document not cached: “ + (+new Date() – start) + “<br/>”);

 

// With cache.

var start = +new Date();

var cachedDoc = document; // Cache DOM element.

for (var i = 0; i < limit; i++) {

   var doc = cachedDoc;

}

document.write(“document cached: “ + (+new Date() – start) + “<br/>”);

 

Summary: When doing something in a loop, if you see a dot or DOM element, cache it!

Comments (1)

  1. Joe says:

    My photos are suspended roughly 4,000 +

Skip to main content