Replicate String in C#

My original posting on string repetition caused a couple responses, and is currently among the Top Posts, which indicates to me that this seems to be a frequent and non-trivial problem.

The .Net API requires that we need to handle two different cases:

Replicating Chars

If you need to replicate a character value, reader Chris points out correctly that the string constructor

s = new string(’*', count);

is to be used.

Replicating Strings

I found the code used in the original posting to replicate an array and convert it to a string afterwards somewhere on the web. What I did not like abound that one-liner was that it allocated first the array, and then the string, resulting in double the memory which should be necessary.

Reader StewartFip posted the StringBuilder.Insert method as a solution, which seems to do the job:

new StringBuilder().Insert(0,”myString”,count).ToString()

Comparison

My guess was that allocating enough memory in the StringBuilder constructor should speed up the Insert(). Actually, it was NOT!

A small benchmarking application showed consistently, that the fastest way is to use StringBuilder.Insert(), a couple percent faster than new StringBuilder(totalsize).Insert(), and the array-to-string conversion taking twice as long.

Like this:

LikeLoading...

Related

This entry was posted on Tuesday, May 6th, 2008 at 20:43 and is filed under .Net, C#. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.