Fastest way to replace multiple strings in a huge string

后端 未结 8 736
野的像风
野的像风 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:05

    It sounds like you are tokenising the string? I would look at producing a buffer and indexing your tokens. Or using a templating engine

    As a naive example you could use code generation to make the following method

    public string Produce(string tokenValue){
    
        var builder = new StringBuilder();
        builder.Append("A");
        builder.Append(tokenValue);
        builder.Append("D");
    
        return builder.ToString();
    
    }
    

    If your running the iterations enough times, the time to build the template will pay for itself. You can then also call that method in parallel with no side effects. Also look at interning your strings

提交回复
热议问题