如何在Javascript中有效地构造巨大的字符串?

如何在Javascript中有效地构造巨大的字符串?,javascript,string,Javascript,String,我正在构建一封警报电子邮件的内容,其中可能包含大量数据 我知道字符串是不可变的。在Java中,我将使用StringBuilder。但是,在Javascript中,最好的方法是什么 我知道下面的方法,我想知道在内存消耗和处理时间方面,哪种方法更有效 方法0: acc = ""; lotsOfItems.forEach(c => acc += toHTML(c)) 方法1: lotsOfItems.reduce((acc,c)=>acc+toHTML(c),"") 方法2: lots

我正在构建一封警报电子邮件的内容,其中可能包含大量数据

我知道字符串是不可变的。在Java中,我将使用StringBuilder。但是,在Javascript中,最好的方法是什么

我知道下面的方法,我想知道在内存消耗和处理时间方面,哪种方法更有效

方法0:

acc = "";
lotsOfItems.forEach(c => acc += toHTML(c))
方法1:

lotsOfItems.reduce((acc,c)=>acc+toHTML(c),"")
方法2:

lotsOfItems.map(x=>toHTML(x)).join("")
我想知道缓冲区或流是否是更好的方式

==加法1===

这个问题也适用于toHTML,它也需要处理巨大的数组

==加法2===

如评论中所问,这里包含了toHTML的实际代码

    const summary = location_alertMessages.map(([location_id, alertMessages]) =>
      `<h2>Location ID: ${location_id}</h2>`
      + "<table><thead><th>Time</th><th>Incident</th></thead><tbody>"
      /* table row begin */
      + alertMessages.reduce((acc, c) => acc + `<tr><td>${formatDate(c.alert_timestamp)}</td><td>${c.title}</td></tr>`, "")
      /* table row end */
      + "</tbody></table>"
    ).join("");

    const detail = location_alertMessages.map(([location_id, alertMessages]) =>
      `<h2>Location ID: ${location_id}</h2>`
      + alertMessages.reduce((acc, c) => acc + `<h3>${c.title}</h3><p>${c.content}</p>`, "")
    )
      .join("");
const summary=location\u alertMessages.map([location\u id,alertMessages])=>
`位置ID:${Location\u ID}`
+“时间事件”
/*表行开始*/
+reduce((acc,c)=>acc+`${formattate(c.alert\u timestamp)}${c.title}`,“”)
/*表行结束*/
+ ""
).加入(“”);
const detail=location\u alertMessages.map([location\u id,alertMessages])=>
`位置ID:${Location\u ID}`
+alertMessages.reduce((acc,c)=>acc+`${c.title}${c.content}

`,”) ) .加入(“”);
两者都可以正常工作。JS引擎之间可能存在差异。只要尝试一下,并对您的尝试进行基准测试。toHTML做什么?这是非常关键的。@MotiKorets我在“附加2”中添加的。您确定这是应用程序中的实际瓶颈吗?@Bergi可能不是我的主要瓶颈,但它位于关键路径上