I have a string in which I need to replace markers with values from a dictionary. It has to be as efficient as possible. Doing a loop with a string.replace is just going to consume memory (strings are immutable, remember). Would StringBuilder.Replace() be any better since this is was designed to work with string manipulations?
I was hoping to avoid the expense of RegEx, but if that is going to be a more efficient then so be it.
Note: I don't care about code complexity, only how fast it runs and the memory it consumes.
Average stats: 255-1024 characters in length, 15-30 keys in the dictionary.
Yes,
StringBuilder
will give you both gain in speed and memory (basically because it won't create an instance of a string each time you will make a manipulation with it -StringBuilder
always operates with the same object). Here is an MSDN link with some details.Rather than running 15-30 replace operations on the entire string, it might be more efficient to use something like a trie data structure to hold your dictionary. Then you can loop through your input string once to do all your searching/replacing.
My two cents here, I just wrote couple of lines of code to test how each method performs and, as expected, result is "it depends".
For longer strings
Regex
seems to be performing better, for shorter strings,String.Replace
it is. I can see that usage ofStringBuilder.Replace
is not very useful, and if wrongly used, it could be lethal in GC perspective (I tried to share one instance ofStringBuilder
).Check my StringReplaceTests GitHub repo.