get query parameter function charAt vs RegExp

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 = index;
  let char;
  for (; end < url.length; end++) {
    char = url.charAt(end);
    if (char === '&'
      || char === '#') {
      break;
    }
  }
  if (end === index) {
    if (defaultValue !== undefined) {
      return defaultValue;
    }
    return '';
  }
  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('filter[status]', 'https://example.com/search?filter[status]=active')
ready
implement of RegExp
getQueryParam2('filter[status]', 'https://example.com/search?filter[status]=active')
ready

Revisions

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