Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

string.Repeat() – smaller and faster version

Yesterday I wrote about Repeat extension method for strings. Today I offer you shorter and faster version of it.

C#
/// <summary>
/// Repeats the specified string n times.
/// </summary>
/// <param name="instr">The input string.</param>
/// <param name="n">The number of times input string 
/// should be repeated.</param>
/// <returns></returns>
public static string Repeat(this string instr, int n)
{
    if(string.IsNullOrEmpty(instr))
        return instr;
 
    var result = new StringBuilder(instr.Length * n);
    return result.Insert(0, instr, n).ToString();
}

VB.NET


''' <summary>
''' Repeats the specified string n times.
''' </summary>
''' <param name="instr">The input string.</param>
''' <param name="n">The number of times input string 
''' should be repeated.</param>
''' <returns></returns>
<System.Runtime.CompilerServices.Extension> _
Public Shared Function Repeat(instr As String, n As Integer) _
   
As String
 
    If String.IsNullOrEmpty(instr) Then
        Return instr
    End If
    
    Dim result = New StringBuilder(instr.Length * n)
    Return result.Insert(0, instr, n).ToString()
End Function

If you look at the code then you can see that it is possible to avoid writing Repeat method, but you have to pay in readability. Take a look at the following line:


var x = new StringBuilder(instr.Length*n)
            .Insert(0, instr, n)
            .ToString();

 
Look at it  if you like but don’t try it at home. :)
kick it on DotNetKicks.com pimp it Shout it

Comments

Eddie Garmon said:

Hate to blow your bubble but I described the fastest managed way here: weblogs.asp.net/.../351707.aspx

Just wrap that functionality in an extension method if needed, but using string.Join looks clean enough to me.

# May 14, 2009 12:13 PM

DigiMortal said:

Thanks for your feedback Eddie! My bubble is modern stuff - it is elastic and there is also room for many other implementations. :)

Your implementation seems pretty cool and straight.

# May 14, 2009 4:11 PM

Eddie Garmon said:

Good to hear your bubble is elastic. I tend to go around throwing knives and flaming arrows at my own all the time.

# May 15, 2009 10:55 AM

DotNetShoutout said:

Thank you for submitting this cool story - Trackback from DotNetShoutout

# May 24, 2009 10:05 AM

DotNetBurner - Tips & Tricks said:

DotNetBurner - burning hot .net content

# May 24, 2009 10:07 AM

PimpThisBlog.com said:

Thank you for submitting this cool story - Trackback from PimpThisBlog.com

# May 24, 2009 10:09 AM

refrigerator repair said:

Magnificent site. Plenty of helpful info here. I am sending it to several friends ans also sharing in delicious. And certainly, thanks to your sweat!

# September 24, 2011 2:18 AM