Faster JavaScript Trim
I've recently discovered the very interesting Steven Levithan post about the JavaScript's trim function of the String class.
So, here my version:
1 function trim13 (str) { 2 var ws = /\s/, _start = 0, end = str.length; 3 while(ws.test(str.charAt(_start++))); 4 while(ws.test(str.charAt(--end))); 5 return str.slice(_start - 1, end + 1); 6 }
More numbers, please!
I tested my function against the benchmarking page of the original post.
Note: times are expressed in MS and are the average of ten executions per browser.
Update [2008-05-29]: I re-runned all the tests and updated results, because Steven noticed that test suite was wrong (few whitespaces).
| Mac | Windows | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| Safari 3.1 | Firefox 2.0.0.14 | Firefox 3.0b5 | Opera 9.27 | Opera 9.50b2 | Internet Explorer 6 | Internet Explorer 7 | Firefox 2.0.0.14 | Opera 9.27 | Opera 9.50b2 | Average | |
| trim1 | 25 | 40 | 19 | 100 | 93 | 12 | 12 | 38 | 124 | 111 | 57 |
| trim2 | 25 | 52 | 29 | 100 | 98 | 6 | 11 | 44 | 125 | 116 | 61 |
| trim3 | 32 | 54 | 46 | 156 | 148 | 15 | 31 | 57 | 209 | 184 | 93 |
| trim4 | 43 | 43 | 37 | 151 | 139 | 15 | 38 | 49 | 198 | 186 | 90 |
| trim5 | 64 | 102 | 104 | 134 | 116 | 65 | 908 | 323 | 291 | 274 | 238 |
| trim6 | 69 | 115 | 109 | 195 | 171 | 47 | 1.497 | 364 | 436 | 338 | 334 |
| trim7 | 69 | 120 | 107 | 142 | 129 | 31 | 900 | 345 | 330 | 271 | 244 |
| trim8 | 4 | 118 | 104 | 112 | 97 | 4 | 5 | 540 | 255 | 180 | 142 |
| trim9 | 34 | 126 | 116 | 1.825 | 1.218 | 23 | 74 | 113 | 1.667 | 1.417 | 662 |
| trim10 | 0 | 1 | 6 | 5 | 3 | 2 | 1 | 0 | 6 | 0 | 2 |
| trim11 | 2 | 2 | 3 | 11 | 3 | 2 | 2 | 10 | 5 | 7 | 5 |
| trim12 | 1 | 3 | 2 | 4 | 6 | 1 | 2 | 10 | 4 | 4 | 4 |
| trim13 | 0 | 0 | 3 | 1 | 1 | 0 | 1 | 2 | 0 | 5 | 1 |
Please download the benchmark suite, and test against your browsers.
advertising





Posted by Steve on 2008-05-28 22:41:59 UTC (permalink)
Hi Luca, great list of tested browsers! I don't have a Mac at my disposal, so those test results are particularly interesting for me.
I've noted a potential issue with your implementation over on my blog at http://blog.stevenlevithan.com/archives/faster-trim-javascript#comment-21445 . Also, as noted there, you can't accurately claim that an implementation is the fastest unless that holds true with any subject data.
Posted by jx on 2008-06-14 15:13:13 UTC (permalink)
a little change:
function trim13 (str) {
var ws = /\s/, _start = 0, _end = str.length-1;
while(ws.test(str.charAt(_start))) _start++;
if( _start > _end) return '';
while(ws.test(str.charAt(_end))) _end--;
return str.slice(_start , _end );
}
Posted by jx on 2008-06-14 15:40:38 UTC (permalink)
function trim13 (str) {
var ws = /\s/, _start = -1, _end = str.length;
while(ws.test(str.charAt(++_start)));
if( _start >= _end) return '';
while(ws.test(str.charAt(--_end)));
return str.slice(_start , _end);
}