Map vs Foreach

Benchmark created on


Setup

function generateRandomString(length) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  let result = '';
  for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

const arrayData = Array.from({ length: 120 }, () => ({
  id: generateRandomString(Math.floor(Math.random() * (30 - 15 + 1)) + 15),
  ["name-de"]: generateRandomString(Math.floor(Math.random() * (30 - 15 + 1)) + 15)
}));


function getLocalizedValue(resultObject, key, locale){
  const constructedKey = buildKey(key, locale);
  const value = resultObject[constructedKey];

  return value;
}

const buildKey = (key, locale) => {
  const languageCode = locale.split('-')[0];
  return `${key}-${languageCode}`;
};

Test runner

Ready to run.

Testing in
TestOps/sec
foreach

const onResultChange = (results) => {
  const sanitizedArticles= [];
  results.forEach(article => {
    const id = article['id'];
    const name = getLocalizedValue(article, 'name', "de-CH");

    if (id && name && typeof name === 'string') {
      sanitizedArticles.push({ id, name });
    }
  });

  return sanitizedArticles;
};

onResultChange(arrayData);
ready
map
const onResultChange = (results) => {
  const sanitizedArticles = results
    .map((article) => {
      const { id } = article;
      const name = getLocalizedValue(article, 'articlename', "de-CH");

      if (id && typeof name === 'string') {
        return { id, name };
      }

      // Returning null for invalid entries which will be filtered out
      return null;
    })
    .filter((article) => article !== null);

  return sanitizedArticles;
};
onResultChange(arrayData);
ready

Revisions

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