Categories
Javascript

Firefox Array.toString() is very slow

Ran into an interesting problem with JavaScript’s Array.toString() in Firefox.  It’s extremely slow even for a very small array.  Take an array with a single object and you’d like to call toString() to get the type of the contained object.  There are better approaches but for simple uses this might be applied.  In this case toString() of the underlying object simple returns the object’s name.  This is a very common use of toString() on custom objects. In Firefox calling toString() on the Array is nearly ten times slower than calling toString() on the object itself.  In Internet Explorer it’s about three times slower.  Needless to say be very careful with JavaScript’s Array.toString(), as it’s not a transparent call into the underlying objects performance wise.

Internet Explorer 6
anArray.toString() - 1829
anObect.toString() - 625

**Firefox 1.5.0.1
**anArray.toString() - 3093
anObect.toString() - 375

The full test script is posted below.

var anArray = \[\];
var anObject = {};
anObject.toString = function() {return "anObject";};
anArray.push(anObject);

var startTime,endTime,i;
var repeat = 250000;

startTime=new Date().getTime();
for(i = 0; i < repeat; i++) { anArray.toString(); }
endTime=new Date().getTime();
var arrayToStringResult = endTime - startTime;

startTime=new Date().getTime();
for(i = 0; i < repeat; i++) { anObject.toString(); }
endTime=new Date().getTime();
var objectToStringResult = endTime - startTime;

document.write("anArray.toString() - " + arrayToStringResult); document.write("<br/>");
document.write("anObect.toString() - " + objectToStringResult);
Kevin Henrikson

Kevin Henrikson

Kevin has spent his career making annoying but important things work better at scale: enterprise email at Zimbra, mobile productivity (co-founded Acompli, acquired by Microsoft for $200M and became Outlook Mobile), marketplace operations at Instacart, and now healthcare administration as Co-Founder of Pretty Good AI.

Subscribe to my newsletter - Founder Mode