String.Replace() vs. StringBuilder.Replace()

2020-01-25 05:30发布

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.

9条回答
欢心
2楼-- · 2020-01-25 05:55

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.

查看更多
对你真心纯属浪费
3楼-- · 2020-01-25 05:55

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.

查看更多
时光不老,我们不散
4楼-- · 2020-01-25 05:55

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 of StringBuilder.Replace is not very useful, and if wrongly used, it could be lethal in GC perspective (I tried to share one instance of StringBuilder).

Check my StringReplaceTests GitHub repo.

查看更多
登录 后发表回答