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:
function trim13 (str) {
var ws = /\s/, _start = 0, end = str.length;
while(ws.test(str.charAt(_start++)));
while(ws.test(str.charAt(--end)));
return str.slice(_start - 1, end + 1);
}
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.