2

Similar to this question but instead of concatenation, using and array and join. If I am constructing a larger string from many smaller strings, is it more efficient to use template literals or push the strings into an array and use join?

Simple example:

const arrayJoin = [constOne, constTwo, constThree].join(' ');
const templateLiterals = `${constOne} ${constTwo} ${constThree}`

A more complicated example:

const stringValues = {
  a: 'apple',
  b: 'butter',
  c: 'cat',
  d: 'dog',   
  e: 'egg',
  f: 'fly', 
};

const finalString1 = Object.keys(stringValues).map((string, i) => {
  return [string, stringValues[string]].join(': ');
}).join(' ');


const finalString2 = Object.keys(stringValues).reduce((result, string, i) => {
  return `${result}${string}: ${stringValues[string]} `;
}, '');
Phil Mok
  • 3,860
  • 6
  • 24
  • 36
  • 3
    I'm voting to close this question as off-topic because it's about performance and optimization – Mulan Jan 24 '19 at 17:39
  • @user633183 If my question is not good, then why is this one allowed?https://stackoverflow.com/questions/29055518/are-es6-template-literals-faster-than-string-concatenation One compares template literals to concatenation, the other to join. – Phil Mok Jan 24 '19 at 17:57
  • 1
    @plmok61 Template strings should be exactly equivalent to string concatenation. Have you tried to do a benchmark yourself? – Bergi Jan 24 '19 at 18:11
  • @plmok61 thanks for linking – I just voted to close that one too. – Mulan Jan 24 '19 at 18:36

0 Answers0