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

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

... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12396정성태11/3/20208413VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209727오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20208154오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208651오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012747.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202011027디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010763.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202010219오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202011005.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202011233Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20209069오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202010245오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202011143.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208874오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010535VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207937오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202010956.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202010379.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
12377정성태10/15/202011675디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208397오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/20209769Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(&#0165;)' 기호로 나오는 경우 [1]
12374정성태10/14/202014382.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
12373정성태10/14/20209627.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
12372정성태10/13/202011492.NET Framework: 951. C# 9.0 - (5) 로컬 함수에 특성 지정 가능(Attributes on local functions)파일 다운로드1
12371정성태10/13/202010274개발 환경 구성: 519. Visual Studio의 Ctrl+Shift+U (Edit.MakeUppercase) 단축키가 동작하지 않는 경우
12370정성태10/13/202011178Linux: 33. Linux - nmcli를 이용한 고정 IP 설정
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...