Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

String Repeat Method for C#

DZone's Guide to

String Repeat Method for C#

Since C# doesn't have any built-in functions to repeat a string, let's take a look at some common implementations and try to determine which one is best.

· Performance Zone ·
Free Resource

Sensu is an open source monitoring event pipeline. Try it today.

C# doesn't have a built-in function to repeat a string. There are different versions for string.Repeat() available on the internet and it's up to the reader to find out which version works better. Here is the list of most popular implementations I found across the web. I list my findings here with the results of a simple performance test.

String Repeat Implementations

I found these six implementations to be most popular:

  • ForLoop - string is repeated in regular for loop
  • PadLeft - string is repeated using empty string, PadLef() method and Replace() method
  • Replace - string is repeated using String constructor and Replace() method
  • Concat - string is repeated using Concat() method on Enumerable.Repeat()
  • StringBuilderInsert - string is repeated using Insert() method on StringBuilder()
  • StringBuilderAppend - string is repeated using AppendJoin() method on StingBuilder()

The last one is a little bit rare, actually, but I added it here as it also gave great results.

String Repeat Methods

Here is the source code of all six methods. I left out sanity checks and other bullet-proofing to keep methods clean of all additional functionalities.

static string RepeatForLoop(string s, int n)
{
    var result = s;

    for (var i = 0; i < n - 1; i++)
    {
        result += s;
    }

    return result;
}        

static string RepeatPadLeft(string s, int n)
{
    return "".PadLeft(n, 'X').Replace("X", s);
}

static string RepeatReplace(string s, int n)
{
    return new String('X', n).Replace("X", s);
}

static string RepeatConcat(string s, int n)
{
    return String.Concat(Enumerable.Repeat(s, n));
}

static string RepeatStringBuilderInsert(string s, int n)
{
    return new StringBuilder(s.Length * n)
                .Insert(0, s, n)
                .ToString();
}

static string RepeatStringBuilderAppend(string s, int n)
{
    return new StringBuilder(s.Length * n)
                .AppendJoin(s, new string[n+1])
                .ToString();
}


Performance of String Repeat Methods

I ran simple performance tests on all those methods. Here is what I did:

  • Every method was run one million times
  • The test string was simply "Test!"
  • The test string was repeated by all methods 130 times
  • During tests, all programs and services with more impact on machine performance were closed
  • The test code was built on the latest .NET Core in Release mode and run on the console
  • I measured the time that it takes for each method to run one million times

Here are my performance test results. Times are given in milliseconds (divide by 1 thousand to get seconds).

We can clearly see that ForLoop is total overkill. It doesn't have any optimizations and it results in a large number of allocations and buffer copies. It is out of the question to use this method in production. But, be warned — ForLoop works fast and doesn't show any signs of performance problems if it is not used intensively.

Other methods are up to ~6.5 times faster. In all my tests, StringBuilderInsert and StringBuilderAppend gave the best results. StringBuilderAppend was, on all tests, a few hundred milliseconds better than StringBuilderInsert. As it was the winner, I present it here as an extension method you can add to a library:

public static class StringExtensions
{
    public static string Repeat(this string s, int n)
    {
        return new StringBuilder(s.Length * n)
                        .AppendJoin(s, new string[n+1])
                        .ToString();
    }
}


Wrapping Up

There are many implementations available for the string repeat method, and not all of them are equal from a performance perspective. We saw that the most primitive version using for-loop has awful performance while a more cumbersome method using StringBuilder and AppendJoin was the best. If there is more than one implementation available, then it's a good idea to run some tests to see what is the best-peforming implementation and go with this.

Sensu: workflow automation for monitoring. Learn more—download the whitepaper.

Topics:
c# ,performance ,strings ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}