find-location-of-non-match-in-string

Benchmark created on


Description

Test includes:

  • while loop
  • findIndex
  • Regexp

Test created by @Logos based on a https://stackoverflow.com/questions/32858626/detect-position-of-first-difference-in-2-strings

Setup

const a = 'find location of non match in string';
const b = 'find location of non match on string';

Test runner

Ready to run.

Testing in
TestOps/sec
while loop
function findFirstDiffPos(a, b) {
  var i = 0;
  if (a === b) return -1;
  while (a[i] === b[i]) i++;
  return i;
}

findFirstDiffPos(a, b);
ready
findIndex
function findFirstDiffPos(a, b) {
  if (a.length < b.length) [a, b] = [b, a];
  return [...a].findIndex((chr, i) => chr !== b[i]);
}

findFirstDiffPos(a, b)
ready
Regexp
function make_regexp(str) {
  var result = '';
  for (var i = str.length-1; i >= 0; i--)
    result = '(' + str[i] + result + ')?';
  return '^' + result;
}

function findFirstDiffPos(a, b) {
  return a === b ? -1 : b.match(make_regexp(a))[0].length;
}

findFirstDiffPos(a, b)
ready

Revisions

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