C# 超快“邮件合并”类型替换
当需要替换位的文档不变时(一种邮件合并场景),我希望获得一些有关执行替换的最快方法的指示。
当然,有很多方法可以使用 string.replace 和 regexp 进行替换,但看起来它们每次寻找匹配时都需要解析输入文档。这就是我试图优化的一点。
I hoping for some pointers on the quickest way to do a replace when the document that needs bits replacing is constant (a sort of mailmerge scenario).
Of course there are lots of ways of doing replaces using string.replace and regexp but it looks like they need to parse the input document each time looking for the match. That's the bit I'm trying to optimise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想说你最好的选择可能是将文档分割成一个数组,每个元素都是前一个替换和下一个替换之间的文本。然后,您只需使用字符串连接将分割数组的内容与每个替换标记交错,而不是替换。
一些伪代码:
I'd say your best bet would probably be to split the document into an array with each element being the text that's in between the previous replacement and the next. Then instead of replacing, you simply interleave the contents of your split array with each of the replacement tokens using string concatenation.
Some pseudocode:
为了提高灵活性,您可以使用 XslCompiledTransform 并让它输出文本。它针对快速 XML 和文本生成进行了优化,如果需要,您也可以包含一些逻辑。
For increased flexibility, you could use a XslCompiledTransform and have it output text. It's optimized for fast XML and text generation, and you could include some logic too if required.
好吧,由于您不想解析并且输入文档是恒定的,因此您可以使用 MemoryStream 来处理原始文档并通过使用其绝对位置来更改位。
另一种方法是使用 String.Format 标记作为占位符:
Well, as you don't want to parse and your input document is constant, you could use a
MemoryStream
to handle your original document and change your bits by using their absolute position.Another way could be use that
String.Format
markers as placeholders: