Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - Collection 식을 지원하는 사용자 정의 타입을 CollectionBuilder 특성으로 성능 보완

컬렉션 식이 C# 12에 추가됐었는데요,

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

위의 글에서도 설명했듯이, 사용자 정의 타입에 대한 컬렉션 식을 지원하는 것이 가능합니다.


using System.Collections;

internal class Program
{
    static void Main(string[] args)
    {
        MyType list = [1, 2, 3, 4, 5, 6, 7, 8];
    }
}

public class MyType : IEnumerable // 1. IEnumerable을 구현한 경우
{
    List<int> _values { get; set; } = new List<int>();

    public IEnumerator GetEnumerator()
    {
        return _values.GetEnumerator();
    }

    public void Add(int value) // 2. "Add" 이름을 갖는 메서드 추가 (확장 메서드로 구현해도 OK)
    {
        _values.Add(value);
    }
}

그런데, 여기서 약간 아쉬운 점이 하나 있다면? "Add" 메서드를 이용한 초기화를 하다 보니 그다지 효율적인 코드가 나오지 않는다는 점입니다.

// 컬렉션 식을 사용한 경우, C# 컴파일러가 생성한 코드

MyType list = new MyType();
list.Add(1);
// ...[생략: 2, 3, 4, 5, 6, 7에 대해 동일하게 Add 호출]...
list.Add(8);

바로 저 문제를 해결하는 방법이 CollectionBuilder 특성을 통해 제공됩니다. 따라서 대충 다음과 같이 변경해 주면,

[CollectionBuilder(typeof(MyTypeCollectionBuilder), nameof(MyTypeCollectionBuilder.Create))]
public class MyType : IEnumerable<int>
{
    List<int> _values = new List<int>();

    public MyType(ReadOnlySpan<int> elems)
    {
        _values.AddRange(elems);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _values.GetEnumerator();
    }

    public IEnumerator<int> GetEnumerator()
    {
        return ((IEnumerable<int>)_values).GetEnumerator();
    }
}

public static class MyTypeCollectionBuilder
{
    public static MyType Create(ReadOnlySpan<int> items) => new MyType(items);
}

C# 컴파일러는 이것을 인지하고, 컬렉션 식으로 초기화하는 코드를 다음과 같이 생성해 줍니다.

MyType list = MyTypeCollectionBuilder.Create(
    RuntimeHelpers.CreateSpan<int>(fieldof(...1~8까지의 숫자를 포함하고 있는 바이너리 영역의 위치...).FieldHandle)
);

보는 바와 같이 컬렉션 식으로 개발자가 명시한 "[1, 2, 3, 4, 5, 6, 7, 8]" 배열 값을 컴파일 시에 미리 바이너리에 저장한 영역으로 대신하고, 그 저장소 공간을 ReadOnlySpan<int>로 받아 사용자가 원하는 코드(위의 경우 AddRange)로 바로 초기화하게 됩니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로, CollectionBuilder로 지정하는 타입은 꼭 분리할 필요까진 없습니다. 즉, 위의 코드를 다음과 같이 하나의 타입에 정의해도 무방합니다.

[CollectionBuilder(typeof(MyType), nameof(Create))]
public class MyType : IEnumerable<int>
{
    List<int> _values = new List<int>();

    public MyType(ReadOnlySpan<int> elems)
    {
        _values.AddRange(elems);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _values.GetEnumerator();
    }

    public IEnumerator<int> GetEnumerator()
    {
        return ((IEnumerable<int>)_values).GetEnumerator();
    }

    public static MyType Create(ReadOnlySpan<int> items) => new MyType(items);
}

관심 있으신 분들은 아래의 글도 읽어보시고. ^^

Adding support for collection expressions to your own types
; https://andrewlock.net/behind-the-scenes-of-collection-expressions-part-5-adding-support-for-collection-expressions-to-your-own-types/




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/6/2024]

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

비밀번호

댓글 작성자
 




... 76  77  [78]  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11986정성태7/17/201916890오류 유형: 557. 드라이브 문자를 할당하지 않은 파티션을 탐색기에서 드라이브 문자와 함께 보여주는 문제
11985정성태7/17/201917039개발 환경 구성: 452. msbuild - csproj에 환경 변수 조건 사용 [1]
11984정성태7/9/201925564개발 환경 구성: 451. Microsoft Edge (Chromium)을 대상으로 한 Selenium WebDriver 사용법 [1]
11983정성태7/8/201914907오류 유형: 556. nodemon - 'mocha' is not recognized as an internal or external command, operable program or batch file.
11982정성태7/8/201914997오류 유형: 555. Visual Studio 빌드 오류 - result: unexpected exception occured (-1002 - 0xfffffc16)
11981정성태7/7/201918077Math: 64. C# - 3층 구조의 신경망(분류)파일 다운로드1
11980정성태7/7/201928186개발 환경 구성: 450. Visual Studio Code의 Java 확장을 이용한 간단한 프로젝트 구축파일 다운로드1
11979정성태7/7/201918457개발 환경 구성: 449. TFS에서 gitlab/github등의 git 서버로 마이그레이션하는 방법
11978정성태7/6/201917689Windows: 161. 계정 정보가 동일하지 않은 PC 간의 인증을 수행하는 방법 [1]
11977정성태7/6/201922295오류 유형: 554. git push - error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413 Request Entity Too Large
11976정성태7/4/201916652오류 유형: 553. (잘못 인증 한 후) 원격 git repo 재인증 시 "remote: HTTP Basic: Access denied" 오류 발생
11975정성태7/4/201925444개발 환경 구성: 448. Visual Studio Code에서 콘솔 응용 프로그램 개발 시 "입력"받는 방법
11974정성태7/4/201921181Linux: 22. "Visual Studio Code + Remote Development"로 윈도우 환경에서 리눅스(CentOS 7) C/C++ 개발
11973정성태7/4/201919920Linux: 21. 리눅스에서 공유 라이브러리가 로드되지 않는다면?
11972정성태7/3/201923723.NET Framework: 847. JAVA와 .NET 간의 AES 암호화 연동 [1]파일 다운로드1
11971정성태7/3/201919989개발 환경 구성: 447. Visual Studio Code에서 OpenCvSharp 개발 환경 구성
11970정성태7/2/201918586오류 유형: 552. 웹 브라우저에서 파일 다운로드 후 "Running security scan"이 끝나지 않는 문제
11969정성태7/2/201919062Math: 63. C# - 3층 구조의 신경망파일 다운로드1
11968정성태7/1/201925757오류 유형: 551. Visual Studio Code에서 Remote-SSH 연결 시 "Opening Remote..." 단계에서 진행되지 않는 문제 [1]
11967정성태7/1/201919807개발 환경 구성: 446. Synology NAS를 Windows 10에서 iSCSI로 연결하는 방법
11966정성태6/30/201918756Math: 62. 활성화 함수에 따른 뉴런의 출력을 그리드 맵으로 시각화파일 다운로드1
11965정성태6/30/201919352.NET Framework: 846. C# - 2차원 배열을 1차원 배열로 나열하는 확장 메서드파일 다운로드1
11964정성태6/30/201920902Linux: 20. C# - Linux에서의 Named Pipe를 이용한 통신
11963정성태6/29/201920638Linux: 19. C# - .NET Core Unix Domain Socket 사용 예제
11962정성태6/27/201918302Math: 61. C# - 로지스틱 회귀를 이용한 선형분리 불가능 문제의 분류파일 다운로드1
11961정성태6/27/201917829Graphics: 37. C# - PLplot - 출력 모음(Family File Output)
... 76  77  [78]  79  80  81  82  83  84  85  86  87  88  89  90  ...