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


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.

Thank you everybody for your feedback!

3 Responses to Replicate String in C#

  1. Thanks for the post (and your previous post) on the repeating string in C#.

  2. robert says:

    another way to replicate is the Clone(); method. this is the best and most practical way of replicating an object taking performance into consideration.

  3. Social bookmark…

    Replicate String in C# « devioblog…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: