Firefox Array.toString() is very slow

0 Flares Twitter 0 Facebook 0 Google+ 0 Buffer 0 LinkedIn 0 0 Flares ×

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);

0 Flares Twitter 0 Facebook 0 Google+ 0 Buffer 0 LinkedIn 0 0 Flares ×
Kevin Henrikson

Kevin Henrikson

Co-Founder Acompli (now Outlook iOS/Android) at Microsoft
Kevin Henrikson leads engineering for Microsoft Outlook iOS/Android. Previously, he co-founded Acompli and ran engineering prior to an acquisition by Microsoft in 2014 for $200M. Before Acompli, he was an Entrepreneur-in-Residence for Redpoint Ventures, a venture capital firm for early stage technology companies.
Kevin Henrikson

@KevinHenrikson

VP Engineering @instacart was Outlook @microsoft, Co-Founder @acompli, EIR @redpoint.
Meet the Second You | Double https://t.co/3RGXsQfod4 - 12 months ago
Kevin Henrikson
Kevin Henrikson