PDA

View Full Version : Testing String Concatenation


fside
02-17-2009, 01:35 AM
The conventional wisdom, as I once read it, suggested avoiding the concatenation operator in preference of an array of strings concatenated with "join()". The idea was that Javascript would have to first convert each primitive to a String object. And that would be overhead.

I recently wondered about it. I wanted to test concatenation, and not loop overhead. So I tested with 72 short strings inside the loop. Now, many of the string were duplicates, for cut n paste convenience. If this skews the results, I don't know. In addition, the loop is called 50K times. Whatever overhead is present, again, I don't know.

But as shown, and I had to break the spreadsheet analysis in two because of upload size limits on this site (the test script and the Excel analysis are in the zip file), five tests were used of the operator and two methods, join and concat. In two of these, the operator and concat were tested using intermediate assignments each step of the way. Needlesstosay, the overhead of assignment shows in the results, though the differences between browsers are great in this and in the rest (one can see the old NN 4.7 really penalized assignment).

For the received wisdom, then, it does appear that IE and Safari's webkit, at least as ported to and run on XP and Win2K, slightly favor the array join approach. But it's not by much over just stringing out the 'plus' operator and assigning the result just once to a variable.

In fact, Firefox 3.06 in either XP or Win2k churns out the concat operator test almost instantly, with no time expiring at all. As for the IE 6 under a Win98SE image in VPC, that's certainly strange. But one just ought then not to use it in a Microsoft VPC.

fside
02-17-2009, 01:41 AM
I just noticed that I was a bit sloppy with the analysis section, using a bracket format if the run was faster than the concat operator test alone, but then showed, above, only fractions if the run was faster than the same on Firefox 3.06 XP as the standard. So, an oversight - and maybe an 'exercise for the reader'.