replace or forEach or for..of (v2)

Revision 2 of this benchmark created on


Setup

const template = `Olá {{1}} 😄 
Esse é um teste utilizando modelos {{1}} com imagens e botões
Enviado pelo {{2}}`;

const variables = [
  {
    "type": "text",
    "text": "Daniel"
  },
  {
    "type": "text",
    "text": "Atendimento Boti"
  }
]

function mergeParamsWithTemplateReplace(templatePlaceholder, variables, kind) {
    return templatePlaceholder.replace(/\{\{(\d)\}\}/gm, (_match, p1) => {
      return `${variables[p1 - 1][kind]}`;
    });
  };
  
function mergeParamsWithTemplateForEach(templatePlaceholder, variables, kind) {
  variables.forEach((param, index) => {
    const reg = new RegExp(`\\{\\{${index + 1}\\}\\}`, 'gm');
    templatePlaceholder = templatePlaceholder.replace(reg, param[kind]);
  });
  return templatePlaceholder;
}

function mergeParamsWithTemplateForOf(templatePlaceholder, variables, kind) {
  let index = 0;
  for (const item of variables) {
    index += 1;
    templatePlaceholder = templatePlaceholder.replace(new RegExp(`\\{\\{${index}\\}\\}`, 'gm'), item[kind]);
  }
  return templatePlaceholder;
}

function mergeParamsWithTemplateFor(templatePlaceholder, variables, kind) {
  for (let index = 0; index < variables.length; index++) {
    const param = variables[index];
    templatePlaceholder = templatePlaceholder.replace(new RegExp(`\\{\\{${index + 1}\\}\\}`, 'gm'), param[kind]);
  }
  return templatePlaceholder;
}

Test runner

Ready to run.

Testing in
TestOps/sec
replace
mergeParamsWithTemplateReplace(template, variables, "text");
ready
forEach
mergeParamsWithTemplateForEach(template, variables, "text");
ready
for of
mergeParamsWithTemplateForOf(template, variables, "text");
ready
for
mergeParamsWithTemplateFor(template, variables, "text");
ready

Revisions

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