dynamic templating (v4)

Revision 4 of this benchmark created on


Setup

const fnTemplate = (template, parameters) => {
  const names = Object.keys(parameters);
  const values = Object.values(parameters);
  return new Function(...names, `return \`${template}\`;`)(...values);
};

const regexTemplate = (template, parameters) => {
  return Object.entries(parameters).reduce(
    (result, [arg, val]) => result.replace(`$\{${arg}}`, `${val}`),
    template
  );
};

const regexNoReduceTemplate = (template, parameters) => {
  for(const key in parameters) {
  	template = template.replace(`$\{${key}}`, `${parameters[key]}`)
  }
  return template;
};

const rawTemplate = (template, parameters) => {
	let start = 0;
	while((start = template.indexOf("${", start)) !== -1) {
		let end = template.indexOf("}", start);
		if(end === -1) {
			break;
		}
		const name = template.slice(start + 2, end);
        const value = String(parameters[name]);
		template = template.slice(0, start) + value + template.slice(end + 1);
        start += value.length;
	}
	return template;
}

Test runner

Ready to run.

Testing in
TestOps/sec
function
fnTemplate("my name is ${name} and i am ${age} years old", {name: "rodr", age: 22})
ready
regex
regexTemplate("my name is ${name} and i am ${age} years old", {name: "rodr", age: 22})
ready
low
rawTemplate("my name is ${name} and i am ${age} years old", {name: "rodr", age: 22})
ready
regex without reduce
regexNoReduceTemplate("my name is ${name} and i am ${age} years old", {name: "rodr", age: 22})
ready

Revisions

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