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

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

... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12410정성태11/12/202017582디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202019424.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202034672도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202019769.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202020755.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202018626.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202019249.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202018153.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202019641.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202018908VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202015135오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202018658.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202018167오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202018188.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202015208VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202017985오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202015616오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202015282오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202019825.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202019478디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202018624.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202017674오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202018461.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202019201Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/202016547오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202018871오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...