简体   繁体   中英

What's the best/fastest way to find the number of tabs to start a string?

I want to find the number of tabs at the beginning of a string (and of course I want it to be fast running code ;) ). This is my idea, but not sure if this is the best/fastest choice:

//The regular expression
var findBegTabs = /(^\t+)/g;

//This string has 3 tabs and 2 spaces: "<tab><tab><space>something<space><tab>"
var str = "      something  ";

//Look for the tabs at the beginning
var match = reg.exec( str );

//We found...
var numOfTabs = ( match ) ? match[ 0 ].length : 0;

Another possibility is to use a loop and charAt:

//This string has 3 tabs and 2 spaces: "<tab><tab><space>something<space><tab>"
var str = "      something  ";

var numOfTabs = 0;
var start = 0;

//Loop and count number of tabs at beg
while ( str.charAt( start++ ) == "\t" ) numOfTabs++;

In general if you can calculate the data by simply iterating through the string and doing a character check at every index, this will be faster than a regex which much build up a more complex searching engine. I encourage you to profile this but I think you'll find the straight search is faster.

Note: Your search should use === instead of == here as you don't need to introduce conversions in the equality check

function numberOfTabs(text) {
  var count = 0;
  var index = 0;
  while (text.charAt(index++) === "\t") {
    count++;
  }
  return count;
}

Try using a profiler (such as jsPerf or one of the many available backend profilers ) to create and run benchmarks on your target systems (the browsers and/or interpreters you plan to support for your software).

It's useful to reason about which solution will perform best based on your expected data and target system(s); however, you may sometimes be surprised by which solution actually performs fastest, especially with regard to big-oh analysis and typical data sets.

In your specific case, iterating over characters in the string will likely be faster than regular expression operations.

One-liner (if you find smallest is best):

"\t\tsomething".split(/[^\t]/)[0].length;

ie splitting by all non-tab characters, then fetching the first element and obtaining its length.

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