Regex indexof short

Benchmark created by Peter van der Zee on


Description

Getting the first position of a regular expression in a string. This is the short version meaning it's tested on short strings. The theory is that it's going to significantly matter on long strings.

See http://jsperf.com/regex-indexof-long

Preparation HTML

<script>
  String.prototype.regexIndexOf_1 = function(regexBody, start) {
        if (typeof regexBody != 'string') regexBody = regexBody.toString().slice(1,-1); // if not a string, then convert regex to string (but only take body)
        if (typeof start != 'number' || start < 0) start = 0;
        for (var i=start,len=this.length; i<len; ++i) {
                if (new RegExp('^.{'+i+'}'+regexBody, '').test(this)) {
                        return i;
                }
        }
        return -1;
  };
  
  String.prototype.regexIndexOf_2 = function(regexBody, start) {
        if (typeof regexBody != 'string') regexBody = regexBody.toString().slice(1,-1);
        if (typeof start != 'number' || start < 0) start = 0;
        for (var i=start,len=this.length; i<len; ++i) {
                if (RegExp('^.{'+i+'}'+regexBody, '').test(this)) {
                        return i;
                }
        }
        return -1;
  };
  
  // lastIndexOf is easy: just make the .* greedy
  String.prototype.regexIndexOf_3 = function(regexBody, pos) {
        if (typeof regexBody != 'string') regexBody = regexBody.toString().slice(1,-1); // if not a string, then convert regex to string (but only take body)
        var startIgnore = '';
        if (typeof pos != 'number' || pos < 0) pos = 0;
        else startIgnore = '.{'+pos+'}';
        var result = new RegExp('^'+startIgnore+'(.*?)'+regexBody, '').exec(this);
        if (result && result[1]) return pos + String(result[1]).length;
        return -1;
  };
  
  // slipsum.com
  var testString = "My money's in that office, right? If she start giving me some bullshit about it ain't there, and we got to go someplace else and get it, I'm gonna shoot you in the head then and there. Then I'm gonna shoot that bitch in the kneecaps, find out where my goddamn money is. She gonna tell me too. Hey, look at me when I'm talking to you, motherfucker. You listen: we go in there, and that nigga Winston or anybody else is in there, you the first motherfucker to get shot. You understand?";
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
for-loop new RegExp
testString.regexIndexOf_1('Winston');
ready
for-loop RegExp
testString.regexIndexOf_2('Winston');
ready
for-loop new RegExp, from
testString.regexIndexOf_1('Winston',2);
ready
.*
testString.regexIndexOf_3('Winston');
ready
.* from
testString.regexIndexOf_3('Winston',2);
ready
String#search
testString.search('Winston');
ready

Revisions

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

  • Revision 1: published by Peter van der Zee on