0

I am building the content of an alert email, which can contains huge amount of data.

As I know string is immutable. In Java, I would use StringBuilder. However, in Javascript, what is the best way to do that?

I know below methods, I want to know which one is more effective, in turns of memory consumption and processing time.

Method 0:

acc = "";
lotsOfItems.forEach(c => acc += toHTML(c))

Method 1:

lotsOfItems.reduce((acc,c)=>acc+toHTML(c),"")

Method 2:

lotsOfItems.map(x=>toHTML(x)).join("")

I wonder if Buffer or Stream will be the better way to go.

=== Addition 1 ===

The question also applies to the toHTML, which also need to deal with huge Array.

=== Addition 2 ===

As asked in the comment, here includes the actual code for the 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("");
Beeno Tung
  • 1,058
  • 10
  • 17

0 Answers0