Sunday, February 3rd, 2008
JavaScript Trim Optimizations
Simon found this gem. Steven Levithan wrote about optimizing a JavaScript trim.
As Simon nicely puts it: “it turns out that while regular expressions are great for removing leading whitespace you can do a lot better at trailing whitespace by manually looping backwards from the end of the string.”
Since the differences between the implementations cross-browser and when used with different data are both complex and nuanced (none of them are faster than all the others with any data you can throw at it), here are my general recommendations for a
trimmethod:
- Use
trim1if you want a general-purpose implementation which is fast cross-browser.- Use
trim11if you want to handle long strings exceptionally fast in all browsers.To test all of the above implementations for yourself, try here. Note that times are logged to the Firebug console (if available), and that the benchmarking system is fairly rudimentary. Note also that background processing can cause the results to be severely skewed, so run the test a number of times (regardless of how many iterations you specify), and only consider the fastest results (since averaging the cost of background interference is not very enlightening).
Final note: Some people like to cache regular expressions using global variables, etc., so they can be used repeatedly without recompilation. This does not make much sense for a
trimmethod, because all of the above regexes are so simple that they typically take no more than a nanosecond to compile. Additionally, some browsers automatically cache the most recently used regexes, so a typical loop which usestrimand doesn’t contain a bunch of other regexes will probably not encounter recompilation anyway.












Why is 4 repeating itself?
[code]return str.replace(/^\s+|\s+$/g, ‘’);[/code]
And I tested the following unincluded test case:
[code]return str.replace(/\s+$/g, ‘’);[/code]
It proved to be just as quick as the recommended lengthy alternatives in this post (1ms). Am I missing something?
Also I guess that g modifier in my above piece of code isn’t needed as well…
@balupton: The first one trims both left and right the second one only trims right.
Ah ok. Cheers.
nice