8
TL;DR: I know there is a class called Stringbuilder, both in .NET how much in Java, that allows performing operations on a text without generating a new string for each method call. It would be very convenient to have something similar in Javascript, but I can not find anything similar.
My goal: let’s assume that I have some texts of considerable size on which I wish to perform certain substitution operations. By sizeable size, let’s imagine strings with millions of characters.
I know that Javascript may not seem to be an appropriate technology for this. But I wish to make the replacements in real time, which excludes techniques like leaving a job to operate on a server. I also wish to replace multiple snippets, based on input user’s.
The problem: Javascript replacements turn out to be expensive in memory. Someone corrects me if I’m wrong - but if I have a string that occupies a megabyte, when using the method replace
of the object String
, I’ll have an occupation of two megabytes: one from the original string, which will not cease to exist until the garbage collector claims it, and another from the new string. When executing a new replacement, there will be three megabytes, and so on. In the thousandth amendment, we are already occupying in the vicinity of a Gigabyte.
I am thinking of approximate numbers, and considering that all substitutions are global (I use regular expressions with the modifier g
, i and..: /foo/g
).
Doubt: there is something that plays the role of a StringBuilder
in Javascript? If not, there is some way in which it could be implemented?
Someone made a comment (infezlimente apagado) with a similar project in Code Project. Very interesting for concatenations - and I believe that, with some modifications, you can improve the performance for substitutions as well, I believe that you can facilitate the work of GC in some ways :) +1, and I would like to give another positive vote just because the project is on Github.
– Oralista de Sistemas
still, since then the language has not changed much with respect to strings.
– Oralista de Sistemas
+1 Just note that - although memory usage is actually lower - performance in time is usually significantly worse (Edit: in some environments more, others less, so I observed).
– mgibsonbr