StringPool 類型會實作string實例的可設定集區。 這可用來在從 或 byte 值的緩衝區char建立多個string實例時,將配置降到最低。 它提供一種機制,與插播有些類似string,主要差異在於集區可設定、可重設、以最佳努力原則實作,而且不需要預先具現化string物件,因此在處理暫存緩衝區時也可以儲存初始配置。
平臺 API:StringPool
語法
的主要進入點是 StringPool 其 GetOrAdd(ReadOnlySpan<char>) API,它會傳回 string 符合輸入 ReadOnlySpan<char>內容的實例,可能會從內部集區取得傳回的物件。
例如,假設我們有代表指定 Web 要求的 URL 的輸入 string ,而且我們也想要只擷取 string 主機名的 。 如果我們針對少量主機取得大量的要求,我們可能會想要快取這些 string 實例,我們可以使用 類型來執行此動作 StringPool ,如下所示:
public static string GetHost(string url)
{
// We assume the input might start either with eg. https:// (or other prefix),
// or directly with the host name. Furthermore, we also assume that the input
// URL will always have a '/' character right after the host name.
// For instance: "https://learn.microsoft.com/dotnet/api/system.string.intern".
int
prefixOffset = url.AsSpan().IndexOf(stackalloc char[] { ':', '/', '/' }),
startIndex = prefixOffset == -1 ? 0 : prefixOffset + 3,
endIndex = url.AsSpan(startIndex).IndexOf('/');
// In this example, it would be "learn.microsoft.com"
ReadOnlySpan<char> span = url.AsSpan(startIndex, endIndex);
return StringPool.Shared.GetOrAdd(span);
}
如果要求 string 已存在於快取中,上述方法就完全沒有配置,因為查閱只是使用 ReadOnlySpan<char> 做為輸入,代表輸入 URL string上的檢視。
StringPool使用不同編碼方式剖析原始要求時,例如UTF8,此類型也很有用。 有一個 GetOrAdd 多載會接受輸入 ReadOnlySpan<byte> 和 Encoding 實例,它會使用從集區租用的暫存緩衝區來擷取 ReadOnlySpan<char> 要用於查閱的值。 這再次可大幅減少根據特定使用案例的配置數目。
範例
您可以在單元測試中找到更多範例。