Sunday, February 3rd, 2008
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
trim1if you want a general-purpose implementation which is fast cross-browser.
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 uses
trimand doesn’t contain a bunch of other regexes will probably not encounter recompilation anyway.
Posted by Dion Almaer at 10:51 pm