Created
March 28, 2022 16:48
-
-
Save ogxd/b778aad7eae4b79c5470526978b67ef8 to your computer and use it in GitHub Desktop.
Fast String Concatenation (better than StringBuilder when it can apply)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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