0

I am transforming some string to another string by iterating over characters and appending them to a new string with some modifications (Some characters are ignored and some new strings will be appended during the process). It is now the bottleneck of my application and took 0.65 second for the transform.

Iterating alone is ok and took 0.05 seconds:

let b = 0;
for (let i = 0; i < s.length; i += 1) {
  b += s.charCodeAt(i);
}

But iterating and appending, without any modifications tooks 0.61 which shows problem is addition to string multiple times:

let b = '';
for (let i = 0; i < s.length; i += 1) {
  b += s.charAt(i);
}

How I can speed it up? In Java there is a StringBuilder for this propose, is there something similar for JS? Can pre-allocating a buffer with 2x size of the original string helps? I'm using nodejs and I can even use wasm for a StringBuilder functionality (I can't migrate transform function logic to wasm) but a pure JS solution is preferred.

hamid k
  • 481
  • 4
  • 11
  • This question, **along with the code** is more suited for [codereview](https://codereview.stackexchange.com/) – Cid Sep 06 '21 at 15:31
  • There are hundreds of questions about string concatenation on Stack Overflow. It's a topic that has been bandied about so many times it's noxious. – Heretic Monkey Sep 06 '21 at 15:45
  • Does this answer your question? [Most efficient way to concatenate strings in JavaScript?](https://stackoverflow.com/questions/16696632/most-efficient-way-to-concatenate-strings-in-javascript) – Heretic Monkey Sep 06 '21 at 15:45
  • @Cid the question is not specific to my code and is about speeding up string appends in general. – hamid k Sep 06 '21 at 15:45
  • In both of your example you're iterating and concating – Cid Sep 06 '21 at 16:04

0 Answers0