Regex.Replace,与string.replace或StringBuilder.Replace这是最快的?这是、最快、Replace、Regex

2023-09-03 08:14:15 作者:放纵的笑是我仅剩旳骄傲

我需要替换所有 System.Environment.Newline(S)我的函数返回的字符串中 System.Environment.Newline + \牛逼(因为我试图将缩进),我需要做几次。

I need to replace all System.Environment.Newline(s) in the string returned by my function with System.Environment.Newline + \t (as I am trying to apply indenting) and I need to do this several times.

我的问题是哪一个是最有效的方式做到这一点?

My question is which one is the most efficient way to do this?

我知道的StringBuilder 与string.replace 更快,但我不知道关于 Regex.Replace

I know that StringBuilder is faster than String.Replace but I dont know about Regex.Replace.

推荐答案

如果你只是想在一个字符串做到这一点,我期待与string.replace 要尽可能快地别的。 的StringBuilder 当您要执行一些的单独的的步骤,并希望避免对每一步的中间字符串是非常有用的。

If you're just trying to do it within a single string, I'd expect string.Replace to be as fast as anything else. StringBuilder is useful when you want to perform a number of separate steps and want to avoid creating an intermediate string on each step.

你有没有基准与string.replace 来看看它是否是足够快吗?

Have you benchmarked string.Replace to find out whether or not it's fast enough for you?

我个人只是开始使用常规的前pressions的时候我其实是带有图案处理,而不是人物的只是一个固定的顺序。如果这样做的性能绝对是至关重要的,你可以基准,为井眼轨迹。

I would personally only start using regular expressions when I was actually dealing with a pattern, rather than just a fixed sequence of characters. If the performance of this is absolutely crucial, you could benchmark that as well of course.