regexp vs indexOf vs substr (v101)

Revision 101 of this benchmark created by Jack on


Setup

var string1 = "world belongs to you";
    var string2 = "belongs to you the world";
    var string3 = "World is not found!";

Test runner

Ready to run.

Testing in
TestOps/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
ready
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
ready
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
ready
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
ready
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
ready
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
ready
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
ready

Revisions

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