At the blog Flagrant Badassery I found some very thorough javascript trim research. I was really amazed by his findings. Did you know there’s a (performance) difference between /\s+/ and /\s\s*/? I thought the regular expression engines would optimize these differences away.
Please do read the article, for it’s pretty interesting. After reading the piece, I had two questions. What was the situation on Mac OS, and of course I had to test my own implementation. After coding, I realized the implementation was similar to the trim10 implementation. The code:
var trim12=function(s) { var whitespace = ' \n\r\t\v\f\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000'; var i=0, j=s.length-1; while(i<s.length && whitespace.indexOf(s.charAt(i))!=-1) i++; while(j>i && whitespace.indexOf(s.charAt(j))!=-1) j--; return s.substring(i,j+1); }
It turns out, this code is pretty fast. The difference with trim10 is it only makes one copy of the string.
But now to more interesting territory: How is the Mac doing? These figures are from my old iMac G4 @ 700Mhz, which is serving me well. I couldn’t test for Internet Explorer, since I installed OS X 10.4 from scratch. But it’s dead anyways. So is Netscape 4.
The results:
| Layout engine | WebCore | Gecko | Presto | ||
|---|---|---|---|---|---|
| method\browser | Safari 2.0.4 | Webkit 24064 | Firefox 2.0.0.4 | Camino 1.5 | Opera 9.21 |
| trim1 | 11.9ms | 12.3ms | 6.5ms | 6.8ms | 28.7ms |
| trim2 | 12.8ms | 13.8ms | 10.6ms | 10.3ms | 30.6ms |
| trim3 | 17.1ms | 17.7ms | 15.5ms | 16.6ms | 44.3ms |
| trim4 | 17.9ms | 18.4ms | 16.0ms | 14.8ms | 43.7ms |
| trim5 | 29.4ms | 43.3ms | 29.4ms | 27.8ms | 39.3ms |
| trim6 | 29.6ms | 44.8ms | 38.8ms | 31.9ms | 84.2ms |
| trim7 | 29.3ms | 43.4ms | 25.9ms | 26.6ms | 41.1ms |
| trim8 | 12.2ms | 12.6ms | 29.8ms | 27.7ms | 33.2ms |
| trim9 | 17.5ms | 11.3ms | 32.1ms | 32.5ms | 1038.5ms |
| trim10 | 0.4ms | 0.4ms | 0.3ms | 0.1ms | 0.3ms |
| trim11 | 0.7ms | 0.6ms | 0.9ms | 0.8ms | 1.5ms |
| trim12 | 0.3ms | 0.3ms | 0.3ms | 0.2ms | 0.3ms |
I ran every test 20 times. For every test, I did a “cold start” (loaded the page fresh into memory). After pressing start, I didn’t touch my computer until it was finished. One of the very odd things is, trim9 really takes forever on Opera. Further, there are no surprises. Except maybe the observation, all Mac browsers (well, all three layout engines) perform pretty much the same.
Conclusions:
trim9 for our Opera friendstrim12 is well suited for trimming big strings in all browsersYou can do the tests yourself on the testpage.
updated: The browser doesn’t hang now when you feed it an empty or all whitespace string