4 more Javascript hacks to make your javascript faster

fast like a shark in a car


1. Get rid of those nested loops

Nested loops have a computational complexity of O(n^2). This means that if you have n items, it will take n*n seconds to complete the loop.

// because this loop is nested, it can 
// take up to 100 seconds to complete
for (var i=0; i<10; i+=1) {
for (var j=0; j<10; j+=1) {
console.log(i, j);
}
}

In a real world application, (for instance, the MRI software I’m currently writing) this simply won’t do. Below is a functionally equivilent loop. (check it yourself!) However, we’ve removed the nested loop and thus have made it execute twice as fast.

// better
for (var i=0, j=0; i<10 && j<10; j++, i=(j==10)?i+1:i,j=(j==10)?j=0:j) {
console.log(i, j);
}

Protip: Eliminate the body of the loop to reduce code complexity even further

// best
for (var i=0, j=0; i<10 && j<10; j++, i=(j==10)?i+1:i,j=(j==10)?j=0:j, console.log(i, j)) { }

2. Bit shift instead of multiply

Did you know that at a molecular level, computers can only add (and they can just barely do that) Computers “multiply” by using a combination of expensive logarithmic look up tables and extremely lucky guesses. Since CPU’s are so fast, they can make dozens of guesses per second until they come up with the right answer.

Instead of multiplying, use the bit shift operation. it looks a little more complex, but once you get the hang of it, it’s pretty simple. The formula to multiply x * y is simply x << (y-1)

As a bonus, everyone else will think you’re really smart!

// multiply by 1
[1,2,3,4].forEach(function(n){ return n<<0; }) // 1,2,3,4
// multiply by 2
[1,2,3,4].forEach(function(n){ return n<<1; }) // 2,4,6,8
// multiply by 3
[1,2,3,4].forEach(function(n){ return n<<2; }) // 3,6,9,12
// etc

3. Round real numbers before multiplying them

The trick above is a great time save for integers. But it doesn’t work for so-called “floating point” numbers (FP for short). In this case, computers really SUPER slow. A Multiplication operation (known as a MUX in programming terms) using the two values, 9.52434123 & 2 takes forever (in milliseconds) to compute. You can’t always avoid FP MUX OPs, but there is a trick to speed them up if you can sacrifice a bit of precision. Simply round the number using the toFixed operation.

// pretty  much the same thing but the second line
// is much faster
9.52434123 * 2
9.52434123.toFixed(2) * 2

4. Add a “download firefox now” link to all your web pages

This last hack is more of a work-around. Instead of putting a lot of effort into making your code faster, just ask your users to use something than Internet Explorer. Firefox is the Worlds Fastest Webrowser ™ Encourage users to switch by including this gif on your webpage


Nicholas Ortenzio is a software developer with a difficult to pronounce last name. Click here to read more exciting javascript articles