JavaScript performance tips

Every now and again a question comes up at work as to which of two or more approaches to the same problem in JavaScript performs better. I’ve started using the fantastic site to document these, so I’ll append to this post whenever I add a new test. I hope you find these useful, as they are answering questions that pertain to practical JavaScript usage.

Creating a regex inside and outside a loop

Declaring variables in a loop or outside it

Using hasOwnProperty or testing with undefined and void 0

Using indexOf or substring to test the end of a string

Extend Without Foreach

Tip: Declare regular expressions once and reuse for performance win

A pattern I see quite often in JavaScript is of people using a regular expression in a loop, e.g.


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

The naive assumption is that a regex is some special native thing, like a boolean. However regular expressions have a cost to construct, which you can see in this performance test –

So, if you’re using a regular expression in JavaScript more than once, declare it first and reuse it to see a dramatic performance gain

CSS Box Sizing makes me happy

Quick note: For anyone fighting for years against the CSS box model, where the visible size of an element depends on the sum of it’s width, height AND padding, check out the box-sizing: border-box;. It does exactly what we need, where if you say

.myclass {
width: 100%;
padding: 10px;

then myclass will still take up 100% width of its container, instead of overflowing.

This is what a successful platform launch looks like

… pity it had to happen as a result of a liquidation sale.

WebOS looks to be on it’s last legs, and HP has announced that it’ll never make new WebOS hardware. In the meantime, the fire sale of TouchPads has done fantastic things for us WebOS developers. The image below is a graph of the Flickr Mundo HD sales for 2011.

If only HP had anything resembling courage, rather than wimping out with the revelation that “Competition is hard? What? No one told me! Run away!!”, this sales trend might have actually continued for a long time.

Ah well, I’ll enjoy it while it lasts!

Touchpad Sales of Flickr Mundo HD