Created
January 19, 2024 08:35
-
-
Save ogxd/0b75fa05205ef8222de1e7992ea0be67 to your computer and use it in GitHub Desktop.
Fast String Concatenation
This file contains 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
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