Share via


StringPool

StringPool 형식은 인스턴스에 대해 구성 가능한 풀을 string 구현합니다. 버퍼 또는 byte 값에서 여러 string 인스턴스를 만들 때 할당을 최소화하는 데 사용할 수 있습니다char. 이는 인턴링과 다소 유사한 string 메커니즘을 제공하며, 기본 차이점은 풀을 구성할 수 있고, 다시 설정할 수 있고, 최선의 정책으로 구현되며, 개체를 미리 인스턴스화 string 할 필요가 없으므로 임시 버퍼에서 작업할 때 초기 할당도 저장할 수 있다는 것입니다.

플랫폼 API:StringPool

구문

기본 진입점 StringPoolGetOrAdd(ReadOnlySpan<char>) 내부 풀에서 반환된 개체를 가져오는 입력 ReadOnlySpan<char>내용과 일치하는 인스턴스를 반환 string 하는 API입니다.

예를 들어 지정된 웹 요청의 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 된 항목이 이미 캐시에 있는 경우 입력 URLstring의 보기를 나타내는 입력으로 조회가 수행 ReadOnlySpan<char> 되므로 할당을 전혀 수행하지 않습니다.

이 형식은 StringPool 다른 인코딩(예: UTF8)을 사용하여 원시 요청을 구문 분석할 때도 유용할 수 있습니다. GetOrAdd 풀에서 임대된 임시 버퍼를 사용하여 조회에 사용할 값을 검색하는 입력 ReadOnlySpan<byte>Encoding 인스턴스를 ReadOnlySpan<char> 사용하는 오버로드가 있습니다. 이렇게 하면 특정 사용 사례 시나리오에 따라 할당 수를 크게 줄일 수 있습니다.

예제

단위 테스트에서 더 많은 예제를 찾을 수 있습니다.