Comprehensive Guide to String Repetition in C#: From Basic Construction to Performance Optimization

Nov 22, 2025 · Programming · 11 views · 7.8

Keywords: C# String Repetition | String Constructor | Performance Optimization | LINQ | Programming Best Practices

Abstract: This article provides an in-depth exploration of various methods for string repetition in C#, focusing on the efficient implementation principles of the string constructor, comparing performance differences among alternatives like Enumerable.Repeat and StringBuilder, and discussing the design philosophies and best practices of string repetition operations across different programming languages with reference to Swift language discussions. Through detailed code examples and performance analysis, it offers comprehensive technical reference for developers.

Core Requirements of String Repetition Operations

In software development, there is often a need to repeat a specific string a designated number of times, which is particularly common in scenarios such as generating indentation, separators, and padding characters. Taking indentation generation as an example, developers need to dynamically generate corresponding amounts of indentation strings based on nesting depth, requiring the language to provide concise and efficient string repetition mechanisms.

Native Solutions in C#

C# provides a specialized string constructor new String(char c, int count) for character repetition, which is the most efficient way to achieve string repetition. This constructor directly allocates the required memory space internally and implements rapid character filling through underlying optimizations, avoiding the creation of intermediate objects and garbage collection overhead.

// Using string constructor for character repetition
string dashes = new String('-', 5);
Console.WriteLine(dashes); // Output: "-----"

// Practical application: generating indentation
string indent = new String(' ', 4); // 4-space indentation
string content = "Hello World";
Console.WriteLine(indent + content);

The advantage of this method lies in its underlying implementation that directly manipulates memory, with performance approaching native code levels. For single-character repetition scenarios, this is unquestionably the best choice.

Implementation of Multi-character String Repetition

When needing to repeat multi-character strings rather than single characters, C# provides LINQ-based solutions. In .NET 4.0 and above versions, it can be achieved by combining Enumerable.Repeat and string.Concat:

string indent = "---";
int repeatCount = 3;
string result = string.Concat(Enumerable.Repeat(indent, repeatCount));
Console.WriteLine(result); // Output: "-----------"

Although this method has concise syntax, attention should be paid to its performance characteristics. Enumerable.Repeat creates an iterator, and string.Concat needs to traverse all elements, calculate total length, and finally allocate memory for concatenation. For large-scale repetition operations, there may be performance bottlenecks.

Performance Comparison and Optimization Recommendations

Performance differences among various methods can be identified through benchmarking:

// Performance testing example
public static string RepeatWithConstructor(char c, int count) 
{
    return new string(c, count);
}

public static string RepeatWithLinq(string str, int count) 
{
    return string.Concat(Enumerable.Repeat(str, count));
}

public static string RepeatWithStringBuilder(string str, int count) 
{
    var sb = new StringBuilder(str.Length * count);
    for (int i = 0; i < count; i++)
    {
        sb.Append(str);
    }
    return sb.ToString();
}

Test results indicate: for single-character repetition, the string constructor has optimal performance; for multi-character repetition, pre-allocated StringBuilder generally outperforms the LINQ method, especially when repetition counts are high.

Cross-language Perspective: Relevant Discussions in Swift

Referring to discussions in the Swift language community about string repetition operations reveals differences in design choices across languages. Swift provides the String(repeating: String, count: Int) initializer, but there was a community proposal to introduce the * operator to simplify syntax:

// Current implementation in Swift
let repeatedString = String(repeating: "abc", count: 3) // "abcabcabc"

// Proposed operator overload (not adopted)
// let repeatedString = "abc" * 3 // proposed syntax

This proposal sparked discussions about operator semantic clarity. Opponents argued that the meaning of the * operator between strings and integers is ambiguous: it could mean string repetition or multiplication of character encoding values. Such design considerations reflect the importance strong-typed languages place on semantic clarity.

Best Practices Summary

Based on performance testing and practical application experience, developers are advised to choose appropriate string repetition methods according to specific scenarios:

By understanding the implementation principles and performance characteristics of various methods, developers can make informed trade-offs between code readability and execution efficiency.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.