I need to insert strings at the beginning. Right now I use StringBuilder.Insert(0, stringToInsert)
to insert at front, but it's taking a lot of time (around 2 mins for 80,000 strings).
The append()
method runs a lot faster (30 secs for 80,000 strings), but it's not the order that I need. How can I reverse the order of the strings (and not the string itself) and decrease the insertion time?
Yes, reversing the enumerable is much faster.
For example:
var numStrings = 80000;
var strings = new List<String>();
for(var i = 0; i < numStrings; i++)
{
strings.Add(Guid.NewGuid().ToString());
}
var sw = new Stopwatch();
sw.Start();
var sb = new StringBuilder();
foreach(var str in Enumerable.Reverse(strings))
sb.Append(str);
sw.Stop();
sw.ElapsedMilliseconds.Dump(); // 13 milliseconds
sb.Dump();
sw = new Stopwatch();
sw.Start();
sb = new StringBuilder();
foreach(var str in strings)
sb.Insert(0, str);
sw.Stop();
sw.ElapsedMilliseconds.Dump(); // 42063 milliseconds
sb.Dump();
Presuming you can put them into an array, and nothing can stop you to do it if you have enough memory, Iterate the array of strings using an index in reverse order and then use append. This should be really fast.
StringBuilder s = new StringBuilder()
for(i = array.Length - 1; i >= 0; i--)
{
s.Append(array[i]);
}
Another method would be to use Reverse with Join. But the previous method should do it in a fast manner
string.Join("", array.Reverse())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With