loop-vs-regex

JavaScript performance comparison

Test case created by loop-vs-regex

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
<script>
Benchmark.prototype.setup = function() {
    var str = 'the sky is blue. apples are green.';
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
loop
var para = str.split('.'), // get array of paragraphs
    i = 0, len = para.length, p;
 
for (; i < len; i++) {
  p = para[i].trim(); // make sure there's no additional whitespace
  para[i] = p.substr(0,1).toUpperCase() + p.substr(1, p.length);
}
 
para = para.join('. ').trim(); // put everything back together
 
console.log(para);
//^ "The sky is blue. Apples are green."
pending…
regex
str = str.replace(/([^.]+\.\s?)/g, function(_, para) {
  return para.replace(/^\w/, function(first) {
    return first.toUpperCase();
  });
});
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment