Skip to content

RegEx is slow (can we make faster hex functions?) #251

@davidmurdoch

Description

@davidmurdoch

Noticed a recent attempt at speeding up some functions by switching to RegEx. But RegExes are usually slower than iterating over strings.

For example, this function:

return isString(value) && HEX_ADDRESS_REGEX.test(value);

Is probably about 4-5x slower than something like this:

function isHexAddress(str) {
  if (typeof str !== "string" || str.length !== 42) return false;
  if (str[0] !== '0' || str[1] !== 'x') return false;
  for (let i = 2; i < 42; i++) {
    let code = str.charCodeAt(i);
    // numbers and lowercase a - f
    if (!((code >= 48 && code <= 57) || (code >= 97 && code <= 102))) {
      return false;
    }
  }
  return true;
}

(don't take my word for it. this should be tested further)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions