다음을 통해 공유


StringPool 클래스

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

플랫폼 API:StringPool

구문

주요 진입점 StringPool 은 API GetOrAdd(ReadOnlySpan<char>) 입니다. 이 API는 string 입력 ReadOnlySpan<char>내용과 일치하는 인스턴스를 반환합니다. 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 된 항목이 캐시에 이미 있는 경우 이전 메서드는 전혀 할당되지 않습니다. 조회는 URL 입력을 ReadOnlySpan<char>로 사용하여 string 뷰를 나타냅니다.

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

예제

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