I have a string, which is long, and a sorted dictionary of indexes and values. I should go over the elements in the dictionary and insert the value to the specified index in the string. I wrote the following code, which works fine, but very slow:
private string restoreText(string text){
StringBuilder sb = new StringBuilder(text);
foreach(KeyValuePair<int, string> pair in _tags){
sb.Insert(pair.Key, pair.Value);
}
return sb.ToString();
}
The dictionary might be very big and contain 500,000 elements.
I think that what makes this function slow is the Insert() method. For dictionary of 100,000 elements, it took almost 5 seconds.
Is there a more efficient way to write this method?
Thanks,
Maya
what I don’t get if you have your indices setup so that the insert won’t change the others but as your code says “yes” I’ll assume so too.
Can you test this one:
it only uses append while beeing the same as your original code