TL; DR: I know there is a class called StringBuilder, either at . NET and Java , which allows you to perform operations on a text without generating a new string for each method call. It would be very convenient to have something similar in Javascript, however I can not find anything similar.
My goal: Let's assume that I have some considerable lengths of text on which I wish to perform certain substitution operations. By size, let's imagine strings with millions of characters.
I know that Javascript may not seem like an appropriate technology for this. But I want to do the replacements in real time, which excludes techniques like leaving a job to operate on a server. I also want to replace multiple snippets, based on the input of the user.
The problem: Javascript overrides end up being expensive in memory. Someone correct me if I am wrong - but if I have a string that occupies a megabyte , using the replace
method of the String
object, I will have an occupation of two megabytes : one of the original string, which will not exist until the garbage collector reclaims it, and another one of the new string. When you perform a new replacement, there will be three megabytes , and so on. In the thousandth change, we are already occupying in the vicinity of a gigabyte .
I'm thinking of approximate numbers, and considering that all substitutes are global (I use regular expressions with the g
modifier, ie: /foo/g
).
Doubt: is there anything that plays the role of StringBuilder
in Javascript? If it does not exist, is there any way it could be implemented?