Fastest way to replace multiple strings in a huge string

后端 未结 8 720
野的像风
野的像风 2020-12-13 04:51

I m looking for the fastest way to replace multiple (~500) substrings of a big (~1mb) string. Whatever I have tried it seems that String.Replace is the fastest way of doing

8条回答
  •  抹茶落季
    2020-12-13 05:07

    As I were mildly interested in this problem, I crafted few solutions. With hardcore optimizations it's possible to go down even more.

    To get the latest source: https://github.com/ChrisEelmaa/StackOverflow/blob/master/FastReplacer.cs

    And the output

    -------------------------------------------------------
    | Implementation       | Average | Separate runs      |
    |----------------------+---------+--------------------|
    | Simple               |    3485 | 9002, 4497, 443, 0 |
    | SimpleParallel       |    1298 | 3440, 1606, 146, 0 |
    | ParallelSubstring    |     470 | 1259, 558, 64, 0   |
    | Fredou unsafe        |     356 | 953, 431, 41, 0    |
    | Unsafe+unmanaged_mem |      92 | 229, 114, 18, 8    |
    -------------------------------------------------------
    

    You won't probably beat the .NET guys in crafting your own replace method, it's most likely already using unsafe. I do believe you can get it down by factor of two if you write it completely in C.

    My implementations might be buggy, but you can get the general idea.

提交回复
热议问题