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

前端 未结 9 1550
萌比男神i
萌比男神i 2020-11-28 05:04

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

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 05:52

    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.

提交回复
热议问题