Sunday, February 3rd, 2008

JavaScript Trim Optimizations

Category: JavaScript

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.

Posted by Dion Almaer at 10:51 pm
4 Comments

+++--
3.3 rating from 28 votes

4 Comments »

Comments feed TrackBack URI

Why is 4 repeating itself?

  1. return str.replace(/^\s+|\s+$/g, '');

And I tested the following unincluded test case:

  1. return str.replace(/\s+$/g, '');

It proved to be just as quick as the recommended lengthy alternatives in this post (1ms). Am I missing something?

Comment by balupton — February 4, 2008

Also I guess that g modifier in my above piece of code isn’t needed as well…

Comment by balupton — February 4, 2008

@balupton: The first one trims both left and right the second one only trims right.

Comment by Spocke — February 4, 2008

Ah ok. Cheers.

Comment by balupton — February 4, 2008

Leave a comment

You must be logged in to post a comment.