DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint
  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads

Trending

  • Idempotency Under Concurrency: Why Your Application Check Isn't the Last Line of Defense
  • Beyond Manual Mapping: AI-Orchestrated Governance for Hybrid Cloud
  • How to Hide Sensitive Information Before You Share a File
  • You Do Not Need a PhD to Become an AI Engineer: The Essential Skill Stack

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. String Repeat Method for C#

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.

By 
Gunnar Peipman
·
Jul. 26, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
24.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

Strings Data Types

Published at DZone with permission of Gunnar Peipman. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint
  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook