get query parameter function charAt vs RegExp (v2)

Revision 2 of this benchmark created on


Description

test performance of different implement

Preparation HTML

<script>
function getQueryParam1(name, url, defaultValue) {
  let index = url.indexOf(name);
  if (index < 0 || url.charAt(index + name.length) !== '=') {
    if (defaultValue !== undefined) {
      return defaultValue;
    }
    return '';
  }
  index += name.length + 1;
  let end;
  const endChar1 = url.indexOf('&', index);
  const endChar2 = url.indexOf('#', index);
  if (endChar1 < 0 && endChar2 < 0) {
    end = url.length;
  } else if (endChar1 > 0 && endChar2 > 0) {
    end = Math.min(endChar1, endChar2);
  } else {
    end = Math.max(endChar1, endChar2);
  }
  if (end === index) {
    if (defaultValue !== undefined) {
      return defaultValue;
    }
    return '';
  }
  let char = url.substring(index, end);
  if (char === 'undefined') {
    return '';
  }
  if (char.indexOf('+') >= 0) {
    char = char.replace(/\+/g, ' ');
  }
  return decodeURIComponent(char);
}
function getQueryParam2(name, url = '', defaultValue) {
  name = name.replace(/[\[\]]/g, "\\$&"); // eslint-disable-line
  const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);
  let results = regex.exec(url); // eslint-disable-line
  if (!results || !results[2]) {
    if (defaultValue !== undefined) {
      return defaultValue;
    }
    return '';
  }
  results[2] = results[2].replace(/\+/g, " ");
  if (results[2] === 'undefined') {
    results[2] = '';
  }
  return decodeURIComponent(results[2]);
}

</script>

Setup


Test runner

Ready to run.

Testing in
TestOps/sec
implement of charAt
getQueryParam1('q', 'https://example.com/search?q=%3Cscript%3Ealert(%22xss%22)%3C/script%3E')
ready
implement of RegExp
getQueryParam2('q', 'https://example.com/search?q=%3Cscript%3Ealert(%22xss%22)%3C/script%3E')
ready

Revisions

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