Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast string insertion at front in c#

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?

like image 923
nimbudew Avatar asked Feb 10 '23 15:02

nimbudew


2 Answers

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();
like image 136
Rob Avatar answered Feb 12 '23 04:02

Rob


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())

like image 29
Dorin Avatar answered Feb 12 '23 05:02

Dorin