Firefox 9.0.1 surprised me by showing up my Ω(log n) number-padding algorithm with a Ω(n) loop method when n is small. In every other browser I've seen, the loop is slower, even for small values of n. I know all the browsers are working on optimizing JS, but since all the other, modern browsers are showing the loop to be slower, is there any explanation for the behavior in Firefox 9?
// Ω(log n)
function padNumberMath(number, length) {
var N = Math.pow(10, length);
return number < N ? ("" + (N + number)).slice(1) : "" + number
}
// Ω(n):
function padNumberLoop(number, length) {
var my_string = '' + number;
while (my_string.length < length) {
my_string = '0' + my_string;
}
return my_string;
}
Update: I don't think this is related to the original question, but I just discovered that IE 9 switches behavior when switching from 32- to 64-bit modes. In 32-bit mode, the Math method wins. In 64-bit mode, the Loop method wins. Just thought I should point that out.
Update 2: MAK caught me in his comment below. The math method's not Ω(1), it's probably more like Ω(log n).