Skip to content

Instantly share code, notes, and snippets.

@ogxd
Created March 28, 2022 16:48
Show Gist options
  • Save ogxd/b778aad7eae4b79c5470526978b67ef8 to your computer and use it in GitHub Desktop.
Save ogxd/b778aad7eae4b79c5470526978b67ef8 to your computer and use it in GitHub Desktop.
Fast String Concatenation (better than StringBuilder when it can apply)
using System;
using System.Collections.Generic;
namespace System;
public static class StringConcatenationExtensions
{
/// <summary>
/// Concatenates strings with manamal allocations and good performance.
/// (only the end result string is allocated)
/// </summary>
/// <param name="strings"></param>
/// <returns></returns>
public unsafe static string Concatenate(this string[] strings)
{
int size = 0;
for (int i = 0; i < strings.Length; i++)
{
var str = strings[i];
if (str == null)
continue;
size += str.Length;
}
// We precallocate the string result,
string result = new string(' ', size);
fixed (char* ptr = result)
{
var span = new Span<char>(ptr, size);
int pos = 0;
for (int i = 0; i < strings.Length; i++)
{
var str = strings[i];
if (str == null)
continue;
int len = str.Length;
str.CopyTo(span.Slice(pos, len));
pos += len;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment