Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1112. C# - .NET 6부터 공개된 ISpanFormattable 사용법 [링크 복사], [링크+제목 복사]
조회: 7498
글쓴 사람
정성태 (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)
13600정성태4/18/2024244닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024270닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024282닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024357닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024700닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024824닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024999닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241049닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241202C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241164닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241071Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241138닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241191닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241149오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241293Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241094Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241046개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241149Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241406Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241585개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241136닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241628닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241870닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...