Speed of Singletons
One of the most popular Javascript patterns is the Singleton. It’s extremely useful way to create namespaces and organize your code.
The thing I’ve been wondering, what is the performance cost when using namespaces? I created a loop that sets a variable 1,000,000 times and records the result.
Let’s test it!
Results:
In this chart, I test the three browsers I use (on OSX), Firefox, Safari, and Chrome. The X axis shows how nested the namespaces were during the test. Literal was just the number 5, and Scope is a single variable in the function scope. Unsurprisingly Safari and Chrome are almost identical.The surprising part is how slow firefox was during the tests. Without running the test on more browsers, it leads me to think that there is something wrong with my testing method. I thought maybe that Safari and Chrome realized that the value didn’t change in each loop, so I modified the test to add i each time. Still the speed returned the same result. I’d be surprised if the next version of firefox didn’t bring this up to speed with the other two browsers.
Conclusion:
Should you worry about the speed when using Singletons as namespaces? Not at all. It took looping 1,000,000 times to get results that I could display. Unless you are processing that many items, I wouldn’t worry about the speed. Keep using namespaces and keep the global clean.
The Test Code:
//Lets run some speed tests
var total_runs = 1000000;
var FIVE = 5;
var i = total_runs;
var tmp;
var start = +new Date();
while(i--) {
tmp = 5;
}
var end = +new Date();
$("#d").append("Literal " + (end - start));
i = total_runs;
start = +new Date();
while(i--) {
tmp = FIVE + i;
}
end = +new Date();
$("#d").append("Scope " + (end - start));
i = total_runs;
start = +new Date();
while(i--) {
tmp = NS.FIVE + i;
}
end = +new Date();
$("#d").append("NS.FIVE " + (end - start));
i = total_runs;
start = +new Date();
while(i--) {
tmp = NS.BOO.FIVE + i;
}
end = +new Date();
$("#d").append("NS.BOO.FIVE " + (end - start));
i = total_runs;
start = +new Date();
while(i--) {
tmp = NS.BOO.BAR.FIVE + i;
}
end = +new Date();
$("#d").append("NS.BOO.BAR.FIVE " + (end - start));
i = total_runs;
start = +new Date();
while(i--) {
tmp = NS.BOO.BAR.CAR.FIVE + i;
}
end = +new Date();
$("#d").append("NS.BOO.BAR.CAR.FIVE " + (end - start));
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

A person essentially assist to make seriously posts I’d state. This is the first time I frequented your web page and so far? I amazed with the research you made to create this particular post incredible. Magnificent process!