如何在 C# 中修剪字符串而不分配额外的内存?

问题描述 投票:0回答:1

我有一个字符串

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 工作。

c# string .net-core memory-management garbage-collection
1个回答
0
投票

这就是

ReadOnlySpan
结构和
System.Memory
命名空间的用途

ReadOnlySpan<char> input = "Hello World-";
string result = new string(input.TrimEnd('-'));
Console.WriteLine(result);
© www.soinside.com 2019 - 2024. All rights reserved.