join vs string vs filter

Benchmark created on


Setup

const APP_NAME = 'Testing';

const joinAndIfs = (pageTitle, pageSubtitle) => {
  const titleParts = [APP_NAME];
  if (pageTitle) {
    titleParts.push(pageTitle);
    if (pageSubtitle) titleParts.push(pageSubtitle);
  }
  return titleParts.join(' - ');
}

const joinAndFilters = (pageTitle, pageSubtitle) => {
  const titleParts = [APP_NAME, pageTitle, pageSubtitle];
  return titleParts.filter((s) => !!s).join(' - ');
}

const stringConcat = (pageTitle, pageSubtitle) => {
  let title = APP_NAME;
  if (pageTitle) {
    title += ' - ' + pageTitle;
    if (pageSubtitle) title += ' - ' + pageSubtitle;
  }
  return title;
}

const earlyReturnsConcat = (pageTitle, pageSubtitle) => {
  let title = APP_NAME;
  if (!pageTitle) return title;
  title += ' - ' + pageTitle;
  if (!pageSubtitle) return title;
  title += ' - ' + pageSubtitle;
  return title
}

const earlyReturnsJoinArr = (pageTitle, pageSubtitle) => {
  if (!pageTitle) return [APP_NAME];
  if (!pageSubtitle) return [APP_NAME, pageTitle];
  return [APP_NAME, pageTitle, pageSubtitle];
}

const earlyReturnsJoin = (...args) => {
  return earlyReturnsJoinArr(...args).join(' - ');
}

Test runner

Ready to run.

Testing in
TestOps/sec
joinAndIfs
joinAndIfs();
joinAndIfs('Page');
joinAndIfs('Page', 'Subpage');
ready
joinAndFilters
joinAndFilters();
joinAndFilters('Page');
joinAndFilters('Page', 'Subpage');
ready
stringConcat
stringConcat();
stringConcat('Page');
stringConcat('Page', 'Subpage');
ready
earlyReturnsConcat
earlyReturnsConcat();
earlyReturnsConcat('Page');
earlyReturnsConcat('Page', 'Subpage');
ready
earlyReturnsJoin
earlyReturnsJoin();
earlyReturnsJoin('Page');
earlyReturnsJoin('Page', 'Subpage');
ready

Revisions

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