I’m trying to obfuscate a large amount of data. I’ve created a list of words (tokens) which I want to replace and I am replacing the words one by one using the StringBuilder class, like so:
var sb = new StringBuilder(one_MB_string); foreach(var token in tokens) { sb.Replace(token, 'new string'); }
It’s pretty slow! Are there any simple things that I can do to speed it up?
tokens is a list of about one thousand strings, each 5 to 15 characters in length.
Instead of doing replacements in a huge string (which means that you move around a lot of data), work through the string and replace a token at a time.
Make a list containing the next index for each token, locate the token that is first, then copy the text up to the token to the result followed by the replacement for the token. Then check where the next occurance of that token is in the string to keep the list up to date. Repeat until there are no more tokens found, then copy the remaining text to the result.
I made a simple test, and this method did 125000 replacements on a 1000000 character string in 208 milliseconds.
Token and TokenList classes:
Example of usage:
Output:
Note: This code does not handle overlapping tokens. If you for example have the tokens ‘pineapple’ and ‘apple’, the code doesn’t work properly.
Edit:
To make the code work with overlapping tokens, replace this line:
with this code: