JavaScript Trim Optimizations

Written by on February 3rd, 2008 in Ajax News.

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 trim method:

  • Use trim1 if you want a general-purpose implementation which is fast cross-browser.
  • Use trim11 if 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 trim method, 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 trim and doesn’t contain a bunch of other regexes will probably not encounter recompilation anyway.

Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/228684383/javascript-trim-optimizations

Comments are closed.



Site Navigation