我有一个字符串
input
。我想从中删除最后一个符号。我可以这样做:
static void Main(string[] args)
{
string input = "Hello World-";
string result = input.TrimEnd('-');
Console.WriteLine(result); // Hello World
}
有效,但是
TrimEnd()
在内部调用System.String.FastAllocateString()
。这是有道理的,因为 string
是不可变的数据结构,通常情况下我们不能做任何其他事情。但是,在我的情况下,我不再需要input
,所以我想重用它的内部缓冲区,而不是分配额外的缓冲区,并“要求”GC
最终清理input
缓冲区。它可以减少整体分配,并减少 GC 工作。
这就是
ReadOnlySpan
结构和 System.Memory
命名空间的用途
ReadOnlySpan<char> input = "Hello World-";
string result = new string(input.TrimEnd('-'));
Console.WriteLine(result);