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.