Microsoft MVP성태의 닷넷 이야기
닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [링크 복사], [링크+제목 복사]
조회: 6994
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 9개 있습니다.)
닷넷: 2112. C# 12 - 기본 람다 매개 변수
; https://www.sysnet.pe.kr/2/0/13338

닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
; https://www.sysnet.pe.kr/2/0/13339

닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
; https://www.sysnet.pe.kr/2/0/13341

닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성)
; https://www.sysnet.pe.kr/2/0/13410

닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays)
; https://www.sysnet.pe.kr/2/0/13412

닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
; https://www.sysnet.pe.kr/2/0/13415

닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
; https://www.sysnet.pe.kr/2/0/13427

닷넷: 2151. C# 12 - ref readonly 매개변수
; https://www.sysnet.pe.kr/2/0/13428

닷넷: 2160. C# 12 - Experimental 특성 지원
; https://www.sysnet.pe.kr/2/0/13444




C# 12 - 인라인 배열(Inline Arrays)

현재(2023-09-14) 기능 명세표를 보면 C# 12의 기능이 모두 8개로 확정(및 closed 상태)되었고, Visual Studio 2022 17.8.0 Preview 1.0 환경에서 "ref readonly parameters"를 제외한 7개의 문법을 모두 실습할 수 있습니다.

7개의 구문 중 4개는 알아봤고, 이번엔 남은 3개 중에서 "인라인 배열(Inline Arrays)"에 대해 알아보겠습니다.




인라인 배열은, struct에 대해 InlineArray 특성을 지정하는 경우 C# 언어에서 새롭게 취급하는 배열 타입입니다.

[System.Runtime.CompilerServices.InlineArray(5)]
public struct Buffer
{
    private int _element0; // public 접근을 허용하지만 실용적이지 않음
                           // 필드는 단 한 개만 정의할 수 있음
}

C# 컴파일러는 위와 같은 정의를 내부 필드의 타입 기준으로 InlineArray 특성에 전달된 수(예제에서는 5)만큼 연속적인 공간에 메모리가 할당된 것으로 처리합니다.

즉, 위의 예제에서는 int 타입 4바이트 * 5 = 20바이트가 연속적으로 메모리에 할당이 되는 식입니다. 이후, 사용 방법도 배열과 완전히 동일하게 취급할 수 있습니다.

namespace ConsoleApp1;

internal class Program
{
    static void Main(string[] args)
    {
        {
            Buffer b = new Buffer(); // 새롭게 정의한 배열 타입

            for (int i = 0; i < 5; i ++)
            {
                b[i] = i; // indexer 구문으로 개별 요소 접근

                Console.WriteLine(b[i]);
            }
        }
    }
}

[System.Runtime.CompilerServices.InlineArray(5)]
public struct Buffer
{
    private int _element0;
}

Inline Array 타입은 Length 속성이 없어 위의 코드에서 5개의 요소를 열거하기 위해 하드 코딩으로 5를 지정했는데, 약간 복잡하지만 다음과 같이 구할 수는 있습니다.

int len = Unsafe.SizeOf<Buffer>() / Unsafe.SizeOf<int>();

for (int i = 0; i < len; i ++)
{
    // ...
}

하지만, Span과도 연동이 되므로 이를 이용하는 것이 더 편리합니다.

Buffer b = new Buffer();
Span<int> s = b; // Span을 경유해,

for (int i = 0; i < s.Length; i ++) // s.Length를 사용해 열거
{
    // ...
}




이렇게 만든 인라인 배열 타입을 메서드 내에서 쓰면 당연히 Stack 영역에 할당합니다. 그런 의미에서 봤을 때 기존의 stackalloc과 유사하다고도 볼 수 있습니다.

// InlineArray 사용
Buffer b = new Buffer(); // 스택에 sizeof(int) * 5 크기만큼의 연속된 공간을 할당

// stackalloc 사용
int* ptr = stackalloc int[5]; // 스택에 sizeof(int) * 5 크기만큼의 연속된 공간을 할당

하지만 stackalloc은 unsafe 문맥을 요구하는 반면 InlineArray는 managed(safe) 환경에서 사용할 수 있습니다.

또한, C# 7.3에 추가된 fixed의 기능과 유사하다고도 볼 수 있는데요,

unsafe struct CppStructType
{
    public fixed int fields[5]; // sizeof(int) * 5 크기만큼의 연속된 공간을 할당
}

[System.Runtime.CompilerServices.InlineArray(5)] // sizeof(int) * 5 크기만큼의 연속된 공간을 할당
public struct Buffer
{
    private int _element0;
}

이것 역시 마찬가지로 fixed는 unsafe 문맥을 필요로 하지만 InlineArray는 managed(safe) 환경에서 사용할 수 있습니다.




결국, '음지'에서 천대받던 ^^ "고정 크기 (스택) 배열"을 '양지'로 끌어낸 기능이 바로 InlineArray입니다. 따라서, 이것의 도입으로 인해 1) C/C++과의 Interop을 좀 더 편하게 할 수 있게 되었고, 2) GC의 개입을 줄이기 위해 스택에 좀 더 간편하게 배열을 생성할 수 있게 되었습니다.

한 가지 유의하셔야 할 것은, 당연히 메서드 또는 다른 struct 타입 내에서 사용하는 경우 스택에 할당되기 때문에 자칫 배열 크기를 너무 크게 잡으면 Stack overflow가 발생하므로 주의해야 합니다.

namespace ConsoleApp1;

internal class Program
{
    static unsafe void Main(string[] args)
    {
        Buffer b = new Buffer();
        Console.WriteLine($"b: {b[0]}");
    }
}

[System.Runtime.CompilerServices.InlineArray(1500000)]
public struct Buffer
{
    public byte _element0;
}

/* 출력 결과
Stack overflow.
   at System.Byte.TryFormat(System.Span`1<Char>, Int32 ByRef, System.ReadOnlySpan`1<Char>, System.IFormatProvider)
   at System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted[[System.Byte, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](Byte)
   at ConsoleApp1.Program.Main(System.String[])
*/

반면, class 내에 정의한다면 Heap에 연속적인 배열 공간을 잡게 되므로 크기 제약이 완화됩니다.

namespace ConsoleApp1;

internal class Program
{
    static unsafe void Main(string[] args)
    {
        MyClass m = new MyClass();
        Console.WriteLine(m.Buf[4500000 - 1]); // 정상 실행
    }
}

public class MyClass
{
    public Buffer Buf;
}

[System.Runtime.CompilerServices.InlineArray(4500000)]
public struct Buffer
{
    private int _element0;
}




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/17/2023]

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

비밀번호

댓글 작성자
 



2023-11-10 02시17분
Wrathmark: An Interesting Compute Workload (Part 1)
; https://ricomariani.medium.com/wrathmark-an-interesting-compute-workload-part-1-47d61e0bea43

컴파일 시에 결정되는 크기로 인해 최적화 성능 향상을 엿볼 수 있는 벤치마크입니다.
정성태

... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12855정성태11/13/20216243개발 환경 구성: 605. Azure App Service - Kudu SSH 환경에서 FTP를 이용한 파일 전송
12854정성태11/13/20217796개발 환경 구성: 604. Azure - 윈도우 VM에서 FTP 여는 방법
12853정성태11/10/20216149오류 유형: 766. Azure App Service - JBoss 호스팅 생성 시 "This region has quota of 0 PremiumV3 instances for your subscription. Try selecting different region or SKU."
12851정성태11/1/20217548스크립트: 34. 파이썬 - MySQLdb 기본 예제 코드
12850정성태10/27/20218691오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
12849정성태10/17/20217831스크립트: 33. JavaScript와 C#의 시간 변환 [1]
12848정성태10/17/20218808스크립트: 32. 파이썬 - sqlite3 기본 예제 코드 [1]
12847정성태10/14/20218656스크립트: 31. 파이썬 gunicorn - WORKER TIMEOUT 오류 발생
12846정성태10/7/20218411스크립트: 30. 파이썬 __debug__ 플래그 변수에 따른 코드 실행 제어
12845정성태10/6/20218239.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
12844정성태10/3/20216244오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/20216691스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202125047오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/20218518스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/20218615.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/20219666.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/20219311.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/20218219VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/20217828Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/20219071.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/20217461오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/20216909VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/20217771VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/20216299VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/20218565오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
12829정성태9/5/202110200.NET Framework: 1115. C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능파일 다운로드1
... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...