Global string replacement

JavaScript performance comparison

Test case created by Mathias Bynens

Info

http://javascriptweblog.wordpress.com/2010/11/08/javascripts-dream-team-in-praise-of-split-and-join/ praises the use of .split() and .join() for just about anything in JavaScript.

This test case compares their split/join-based replaceAll method with a simple .replace() using the g modifier.

The article had this to say about replaceAll:

It performs almost as well as the native function (the trade off is two extra function calls against a regex match).

Let’s put it to the test!

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
.split('foo').join('bar') replace
'the man and the plan'.split('the').join('a'); // 'a man and a plan'
pending…
.replace(/foo/g, 'bar')
'the man and the plan'.replace(/the/g, 'a'); // 'a man and a plan'
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

1 comment

Samuel Reed commented :

Interesting results on Chrome 6-8: I've traced it down, for anyone who's interested, to a v8 bug report where they removed caching of RegExp results.

FTA:

"In Chrome 9 we have removed a primitive caching of RegExp results. That means that we no longer take unrealistically low time for repeating the same operation on the same input over and over again. The caching was originally added to make a point about benchmarks that were too simplistic (our own, at that time, included) being too easy to "game" by adding such caching (which makes no difference in real-world scenarios). Most benchmarks have since improved so much that we decided to remove the caching (and its unavoidable overhead). The cache was added in v8 revision 4083 (released in Chrome 5) and removed in revision 5755 (will be in Chrome 9)"

"Just to be clear, it's not the parsing of the regexps, only the parsing by the regexps. The only programs that will be slowed down by this change are programs that repeatedly match the same string against the same regexp. It is not enough for the strings to have identical contents, the optimization only kicked in if it was the identical string.

We believe that this never occurs in real code, only in naïve benchmarks. Therefore the optimization was removed. If you have real code that suffers from the removal of this optimization we would like to hear about it."

Add a comment