简体   繁体   中英

Fastest way to check if substring is at specific position of another string

I have string (length 50-2000) and potential substring (length 2-8) which can only start at specific position (it may occur elsewhere but I don't care). I need to test large number of strings so speed is the key here. Is there faster way then:

var q = baseString.indexOf(searchString, assumedIndex) === assumedIndex; 

or

var q = baseString.substr(assumedIndex, searchString.length) === searchString; 

Keeping in mind what Amit said in the comments, I thought I might as well add an alternative that will (probably) be faster than at least the substr method:

var q = baseString.startsWith(searchString, assumedIndex); 

From MDN :

The startsWith() method determines whether a string begins with the characters of another string, returning true or false as appropriate.

Small example:

> "Hello world!".startsWith("world!",6)
< true

The reason I argue it may be faster is because the polyfill (shown below) is directly what you implemented with substr , except that browser implementations will be implemented natively and probably without string copying. So it should be at least as fast as what you already suggested.

Polyfill:

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(searchString, position){
      position = position || 0;
      return this.substr(position, searchString.length) === searchString;
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM