Skip to content

Instantly share code, notes, and snippets.

@ogxd
Created January 19, 2024 08:35
Show Gist options
  • Save ogxd/0b75fa05205ef8222de1e7992ea0be67 to your computer and use it in GitHub Desktop.
Save ogxd/0b75fa05205ef8222de1e7992ea0be67 to your computer and use it in GitHub Desktop.
Fast String Concatenation
public static class ConcatenateExtensions
{
public static unsafe string Concatenate(this IReadOnlyList<string?> strings)
{
int size = 0;
for (int i = 0; i < strings.Count; i++)
{
string? str = strings[i];
if (str == null)
{
continue;
}
size += str.Length;
}
// We precallocate the string result,
string result = new(' ', size);
fixed (char* ptr = result)
{
var span = new Span<char>(ptr, size);
int pos = 0;
for (int i = 0; i < strings.Count; i++)
{
string? 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