Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1112. C# - .NET 6부터 공개된 ISpanFormattable 사용법 [링크 복사], [링크+제목 복사]
조회: 7491
글쓴 사람
정성태 (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)
13296정성태3/25/20233692Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20233957Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234125.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234193오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234313Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234717.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234222.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233418Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233516Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233686Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234147Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233739Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20233939Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233480오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233818Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233720Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234466개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234011오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/20233969개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20234587개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234313.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20234669.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234260.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20233957.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
13272정성태2/27/20234215오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
13271정성태2/25/20234148오류 유형: 849. Sql Server Configuration Manager가 시작 메뉴에 없는 경우
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...