Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1112. C# - .NET 6부터 공개된 ISpanFormattable 사용법 [링크 복사], [링크+제목 복사]
조회: 7550
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

C# - .NET 6부터 공개된 ISpanFormattable 사용법

ISpanFormattable 인터페이스는,

ISpanFormattable Interface
; https://learn.microsoft.com/en-us/dotnet/api/system.ispanformattable

.NET Repo의 commit 시기로 봤을 때 .NET Core 2.1부터 포함된 것으로 보입니다. 하지만 그동안 internal 접근 상태였다가 .NET 6부터 public으로 풀렸습니다. 이 인터페이스를 보면, 마이크로소프트가 .NET Core의 기본적인 힙 메모리 사용을 얼마나 줄이고 싶어 하는지 느낄 수 있습니다. (어찌 보면, 광적이라는 표현이 적합할지도 모릅니다. ^^;)

이것저것 설명 말고 코드 먼저 보는 게 좋겠죠? ^^ 다음은 ISpanFormattable을 상속한 구조체의 코드로 내부 코드는 .NET Core 6의 구현을 가져와서 대충(가령 음수나 format/provider 처리 없이) 씌워본 것입니다.

using System.Runtime.InteropServices;

Person p = new Person { Age = 25 };

int written = 0;
Span<char> buffer = stackalloc char[100];
p.TryFormat(buffer, out written, null, null); // buffer에 Person 인스턴스의 ToString에 준하는 문자열이 포함됨

public struct Person : ISpanFormattable
{
    public int Age;

    public override string ToString()
    {
        return ToString(null, null);
    }

    public string ToString(string? format, IFormatProvider? formatProvider)
    {
        if (format == null)
        {
            return Age.ToString();
        }

        return string.Format(formatProvider, format, Age);
    }

    public unsafe bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
    {
        return TryFormatInt32(this.Age, -1, format, provider, destination, out charsWritten);
    }

    public static bool TryFormatInt32(int value, int hexMask, ReadOnlySpan<char> format, IFormatProvider? provider, Span<char> destination, out int charsWritten)
    {
        return TryUInt32ToDecStr((uint)value, -1, destination, out charsWritten);
    }

    private unsafe static bool TryUInt32ToDecStr(uint value, int digits, Span<char> destination, out int charsWritten)
    {
        int num = Math.Max(digits, CountDigits(value));
        if (num > destination.Length)
        {
            charsWritten = 0;
            return false;
        }
        charsWritten = num;

        fixed (char* reference = &MemoryMarshal.GetReference<char>(destination))
        {
            char* ptr = reference;
            char* ptr2 = ptr + num;
            if (digits <= 1)
            {
                do
                {
                    ValueTuple<uint, uint> valueTuple = Math.DivRem(value, 10U);
                    value = valueTuple.Item1;
                    uint item = valueTuple.Item2;
                    *(--ptr2) = (char)(item + 48U);
                }
                while (value != 0U);
            }
            else
            {
                ptr2 = UInt32ToDecChars(ptr2, value, digits);
            }
        }
        return true;
    }

    internal unsafe static char* UInt32ToDecChars(char* bufferEnd, uint value, int digits)
    {
        while (--digits >= 0 || value != 0U)
        {
            ValueTuple<uint, uint> valueTuple = Math.DivRem(value, 10U);
            value = valueTuple.Item1;
            uint item = valueTuple.Item2;
            *(--bufferEnd) = (char)(item + 48U);
        }
        return bufferEnd;
    }

    public static int CountDigits(uint value)
    {
        int num = 1;
        if (value >= 100000U)
        {
            value /= 100000U;
            num += 5;
        }
        if (value >= 10U)
        {
            if (value < 100U)
            {
                num++;
            }
            else if (value < 1000U)
            {
                num += 2;
            }
            else if (value < 10000U)
            {
                num += 3;
            }
            else
            {
                num += 4;
            }
        }
        return num;
    }
}

코드에서 알 수 있듯이, ISpanFormattable은 주로 값 형식의 ToString에 대한 힙 할당 문제를 해결하는 목적으로 나온 것입니다. 사실 그동안 제네릭의 지원을 통해 대부분의 경우 박싱 문제를 없애 힙 할당을 많이 줄였지만, 의외로 많이 사용하면서 피해 갈 수 없는 것이 바로 ToString이었습니다. 즉, 다음과 같은 간단한 코드에서조차,

int value = 5;
Console.WriteLine(value);

내부적으로는 value.ToString을 호출해 System.String을 힙에 할당해 처리하게 됩니다. 이런 문제를 마이크로소프트는 위의 코드에서처럼 Span을 이용함으로써 해결하고 있는 것입니다.

실제로 이것은 StringBuilder에 적용돼 기본 타입들에 대해 힙 할당 없이 값을 출력할 수 있는 기능을 제공합니다.

public StringBuilder Append(int value) => AppendSpanFormattable(value);
public StringBuilder Append(long value) => AppendSpanFormattable(value);
public StringBuilder Append(float value) => AppendSpanFormattable(value);
public StringBuilder Append(double value) => AppendSpanFormattable(value);
public StringBuilder Append(decimal value) => AppendSpanFormattable(value);
public StringBuilder Append(ushort value) => AppendSpanFormattable(value);
public StringBuilder Append(uint value) => AppendSpanFormattable(value);

private StringBuilder AppendSpanFormattable<T>(T value) where T : ISpanFormattable
{
    if (value.TryFormat(RemainingCurrentChunk, out int charsWritten, format: default, provider: null))
    {
        m_ChunkLength += charsWritten;
        return this;
    }

    return Append(value.ToString());
}

private Span<char> RemainingCurrentChunk
{
    get => new Span<char>(m_ChunkChars, m_ChunkLength, m_ChunkChars.Length - m_ChunkLength);
}

하지만 아쉽게도 AppendSpanFormattable이 private이기 때문에 사용자 정의 값 형식에 대해서는 박싱이 발생합니다.

Person p = new Person { Age = 32 }; // 구조체 Person

StringBuilder sb = new StringBuilder();
sb.Append(p); // 힙 할당 발생

만약, 위의 상황에서 힙 할당을 없애고 싶다면 멤버 단위로 풀어서 호출하는 식으로 처리해야 합니다.

Person p = new Person { Age = 32 }; // 구조체 Person

StringBuilder sb = new StringBuilder();
sb.Append(p.Age); // 힙 할당 없음!




기타 좀 더 자세한 사항은 다음의 글을 통해 확인할 수 있습니다. ^^

Andrew Lock | .NET Escapades
; https://andrewlock.net/a-deep-dive-on-stringbuilder-part-2-appending-strings-built-in-types-and-lists/

그나저나, 저렇게 처리함으로써 코드는 점점 더 (무거워지고) 복잡해지는데, 과연 힙의 할당량을 줄이는 것이 얼마나 의미가 있길래... 저렇게까지 하는 걸까요? ^^ 종종 있는 ASP.NET Core/5+의 성능 증가 발표를 보면 아마도 저런 과한 노력의 덕분이지 않을까... 하는 예상입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/3/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13531정성태1/16/20242060닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242035닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241914닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242046Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20241979오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242063닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242031오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242082오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20241899오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242044닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242122닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241868오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20241965닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242190닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242038스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242122닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242401닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242069개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242025닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20241997개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242018닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20241953닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20241971오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242028오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242716닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232201닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...