Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1112. C# - .NET 6부터 공개된 ISpanFormattable 사용법 [링크 복사], [링크+제목 복사]
조회: 7654
글쓴 사람
정성태 (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)
13432정성태10/31/20232452오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232788스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232675닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232958닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233033닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233247닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233407스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233193닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233171스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233315닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233393닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235579스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233218스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233922닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233451닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233256오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233754닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233510디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233708닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236987닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233490Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235028닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233885닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233839Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233586닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233552VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...