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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples

Trending

  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  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 user avatar
Gunnar Peipman
·
Jul. 26, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
23.6K Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!