Occurrence Check using RegEx vs for Loop (v3)

Revision 3 of this benchmark created on


Setup

const EMPTY_ARRAY = Object.freeze([]);
const VALUE_PLACEHOLDER_IN_FORMAT = '#';
const REGEX_TO_MATCH_VALUE_PLACEHOLDER = new RegExp(VALUE_PLACEHOLDER_IN_FORMAT, 'g')

const getDigitPlaceholderMatches = (phoneNumberFormat = '') => {
  const digitPlaceholderMatches = phoneNumberFormat.match(REGEX_TO_MATCH_VALUE_PLACEHOLDER);
  return digitPlaceholderMatches;
};

const getCountOfPhoneNumberDigits = phoneNumberFormat => {
  const digitPlaceholderMatches = getDigitPlaceholderMatches(phoneNumberFormat) || EMPTY_ARRAY;

  const countOfPhoneNumberDigits = digitPlaceholderMatches.length;
  return countOfPhoneNumberDigits;
};


var getCountOfPhoneNumberDigitsUsingForLoop = function getCountOfPhoneNumberDigits(phoneNumberFormat) {
  let count = 0;
  
  for(let i = 0; i < phoneNumberFormat; i++) {
    const curr = phoneNumberFormat[i];
    
    if(curr === VALUE_PLACEHOLDER_IN_FORMAT)
      count++;
  }
  
  return count;
};

const phoneNumberFormat1 = "(###) ###-####";

Test runner

Ready to run.

Testing in
TestOps/sec
Using For Loop
getCountOfPhoneNumberDigitsUsingForLoop(phoneNumberFormat1);
ready
Using RegExp
getCountOfPhoneNumberDigits(phoneNumberFormat1);
ready

Revisions

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