Match and Substitute

JavaScript performance comparison

Revision 4 of this test case created by nhahtdh on 17th March 2013

Info

This test compares some ways of substituting parts of a string with new parts provided. In principle, the process should return a string which has any parenthesised digits in it replaced by values taken from the appropriate place in the array.

So given an array consisting of just the words "is" and "test", the result for "this (0) a (1) sentence" should be "this is a test sentence". If anything goes wrong, the result should just return the original or a partially-transformed string.

See an old school match-and-substitute process in action here: http://jsfiddle.net/guypursey/82APF/

[I added a more concise version which is not JSLint-approved but does make the code more concise. I wanted to see if the more concise code was also more efficient.]

See a newer lambda-replace process for the same result here: http://jsfiddle.net/guypursey/8bL8a/

Preparation code

<divid="result"></div><script> Benchmark.prototype.setup=function(){var rgM =/\((\d+)\)/, rgR =/\((\d+)\)/g, str ="This (0) a (1) sentence. This sentence (0) a (1). The result should (2) a sentence (3) any numbers (4) it. Let's (5) what the result actually (0). Crucially, let's (5) if an old style while-loop (0) faster than an anonymous function inside a String.replace() call (3) all those extraneous variables getting (5) the way. This (0) the real (1) of the sentence!", sub =["is","test","be","without","in","see"], result;};