Microsoft MVP성태의 닷넷 이야기
닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [링크 복사], [링크+제목 복사],
조회: 7076
글쓴 사람
정성태 (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

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

1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...
NoWriterDateCnt.TitleFile(s)
13312정성태4/8/20234056Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234537C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234171C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234315.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234216스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233967.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233756Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20234141Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234451VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233824Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234454Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234574Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234219Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20233974Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20233959Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234618Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233943Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20234228Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234391.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234443오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234558Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234949.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234429.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233643Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233756Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233933Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...