regexp vs indexOf vs substr

JavaScript performance comparison

Revision 101 of this test case created by Jack

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var string1 = "world belongs to you";
    var string2 = "belongs to you the world";
    var string3 = "World is not found!";
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
String.prototype.match
var i = 0
if (string1.match(/^world/))++i
if (string2.match(/^world/))++i
if (string3.match(/^world/))++i
if (i !== 1) throw new Error
pending…
String.prototype.indexOf
var i = 0
if (string1.indexOf("world") === 0)++i
if (string2.indexOf("world") === 0)++i
if (string3.indexOf("world") === 0)++i
if (i !== 1) throw new Error
pending…
String.prototype.substr
var i = 0
if (string1.substr(0, 5) === "world")++i
if (string2.substr(0, 5) === "world")++i
if (string3.substr(0, 5) === "world")++i
if (i !== 1) throw new Error
pending…
String.prototype.search
// Note that search expects RegExp and converts string to RegExpes.
// This test just checks cost of converting to RegExp.
var i = 0
if (string1.search("world") === 0)++i
if (string2.search("world") === 0)++i
if (string3.search("world") === 0)++i
if (i !== 1) throw new Error
pending…
String.prototype.search with RegExp
var i = 0
if (string1.search(/^world/) === 0)++i
if (string2.search(/^world/) === 0)++i
if (string3.search(/^world/) === 0)++i
if (i !== 1) throw new Error
pending…
String.prototype.search with RegExp without anchor
var i = 0
if (string1.search(/world/) === 0)++i
if (string2.search(/world/) === 0)++i
if (string3.search(/world/) === 0)++i
if (i !== 1) throw new Error
pending…
lastIndexOf
var i = 0
if (string1.lastIndexOf('world', 0) === 0)++i
if (string2.lastIndexOf('world', 0) === 0)++i
if (string3.lastIndexOf('world', 0) === 0)++i
if (i !== 1) throw new Error
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:

0 comments

Add a comment