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. :)