성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>.NET 6부터 SourceGenerator와 통합된 System.Text.Json</h1> <p> 아래의 질문을 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 익명 클래스 말고 익명 구조체는 불가능한걸까요? ; <a target='tab' href='https://www.sysnet.pe.kr/3/0/5786'>https://www.sysnet.pe.kr/3/0/5786</a> </pre> <br /> 이렇게 직렬화를 하는데,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > string jsonString = JsonSerializer.Serialize(new { Age = 5, Height = 110 }); </pre> <br /> new로 생성한 익명 타입이 class이기 때문에 GC를 줄이기 위한 방법으로 struct가 사용되도록 하는 방법을 묻고 있습니다. 일단, 위의 코드에서 JsonSerializer.Serialize 메서드는 object를 받는 버전과 제네릭을 받는 버전으로 나뉩니다.<br /> <br /> 당연히 object를 받는 버전의 경우 설령 struct를 전달했다고 해도 박싱이 되므로 처음부터 클래스를 쓴 것보다 못한 결과를 낳습니다. 재미있는 건, 위의 메서드를 호출하면 제네릭 버전이 호출되긴 하는데요,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public static string Serialize<TValue>(<span style='color: blue; font-weight: bold'>TValue value</span>, JsonSerializerOptions? options = null) { JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options); return WriteString(value, jsonTypeInfo); } </pre> <br /> 결국 내부 코드에서 호출되는 ObjectDefaultConverter.OnTryWrite 메서드가 박싱을 하기 때문에,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > internal sealed override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) { JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; <span style='color: blue; font-weight: bold'>object obj = value; // box once</span> // ...[생략]... } </pre> <br /> 제네릭 지원 버전이라고 해서 GC Heap 사용이 없는 것은 아닙니다. 그렇긴 해도 System.Text.Json이 내부적으로 어떡해서든 GC Heap의 사용을 줄이려고 최대한 노력했다는 점이 코드 곳곳에서 눈에 띕니다. 가령 직렬화하는 buffer도 <a target='tab' href='https://www.sysnet.pe.kr/2/0/12893'>PooledByteBufferWriter를 이용해 풀링</a>을 시켜놓고 있으며 <a target='tab' href='https://www.sysnet.pe.kr/2/0/11534'>Span<T></a>의 사용과 함께 GC Heap 할당을 억제하고 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 그나저나 .NET 6부터 System.Text.Json에는 JsonTypeInfo을 지원하는 제네릭 버전이 추가되었는데요,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public static string Serialize<TValue>(TValue value, JsonTypeInfo<TValue> jsonTypeInfo) { if (jsonTypeInfo is null) { ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); } jsonTypeInfo.EnsureConfigured(); return WriteString(value, jsonTypeInfo); } </pre> <br /> 이건 <a target='tab' href='https://www.sysnet.pe.kr/2/0/12986'>Source Generator</a>와 연동하므로, 컴파일 시점에 미리 생성해 둔 직렬화/역직렬화 클래스의 도움을 받아 성능을 높이게 됩니다. 게다가 사용 방법이 매우 쉬워서 그래도 나름 쓸만한데요, 예를 들어, 다음과 같이 직렬화할 타입이 있으면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public struct MyPerson { public int Age { get; set; } public int Height { get; set; } } </pre> <br /> 그 타입을 JsonSerializable 특성으로 연결한 JsonSerializerContext의 상속 타입을 "partial"로 새롭게 만들어 주기만 하면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [JsonSourceGenerationOptions(WriteIndented = true)] <span style='color: blue; font-weight: bold'>[JsonSerializable(typeof(MyPerson))]</span> internal <span style='color: blue; font-weight: bold'>partial</span> class SourceGenerationContext : <span style='color: blue; font-weight: bold'>JsonSerializerContext</span> { } </pre> <br /> 끝입니다. 그럼 C# 컴파일러는 (%LOCALAPPDATA%\Temp\VSGeneratedDocuments 하위에) "SourceGenerationContext.MyPerson.g.cs" 파일을 컴파일 시점에 생성하고 "SourceGenerationContext.Default.MyPerson" 속성이 제공되므로 Json 직렬화 시 이것을 활용해,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MyPerson t = new MyPerson { Age = 5, Height = 120 }; string jsonString = JsonSerializer.Serialize(t, <span style='color: blue; font-weight: bold'>SourceGenerationContext.Default.MyPerson</span>); </pre> <br /> JsonSerializer.Serialize 메서드의 2번째 인자에 해당하는 JsonTypeInfo로 전달하면 됩니다. 실제로 이러한 2개의 코드를 <a target='tab' href='https://www.sysnet.pe.kr/2/0/11547'>BenchmarkDotNet</a>으로 확인해 보면 "Source Generator"를 이용한 버전이 더 빠른 것을 확인할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > | Method | Mean | Error | StdDev | |---------------- |----------:|----------:|---------:| | SerializeSrcGen | 80.98 ns | 25.378 ns | 1.391 ns | // Source Generator를 이용한 버전 | SerializeObject | 104.31 ns | 12.104 ns | 0.663 ns | </pre> <br /> 그런데 여기서도 재미있는 점이 하나 있습니다. Source Generator를 이용한 JsonTypeInfo를 전달한 경우에는 당연히 ObjectDefaultConverter.OnTryWrite를 사용하지 않으므로 (구조체를 전달한 경우) 박싱은 발생하지 않습니다. 하지만, 오히려 GC Heap 사용은 class를 전달한 경우보다 더 나옵니다.<br /> <br /> 예를 들어, 최종적으로 다음과 같이 테스트 코드를 구성하고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Running; using System.Text.Json; using System.Text.Json.Serialization; [JsonSourceGenerationOptions(WriteIndented = true)] [JsonSerializable(typeof(MyPerson))] internal partial class SourceGenerationContext : JsonSerializerContext { } public class Person { public int Age { get; set; } public int Height { get; set; } } public struct MyPerson { public int Age { get; set; } public int Height { get; set; } } namespace ConsoleApp1 { [ShortRunJob] [MemoryDiagnoser] public class Program { static int _count = 0; static void Main(string[] args) { BenchmarkRunner.Run<Program>(); } static Person p1 = new Person { Age = 5, Height = 110 }; static MyPerson p2 = new MyPerson { Age = 5, Height = 110 }; [Benchmark] public void SerializeSrcGen() { string jsonString = JsonSerializer.Serialize(p2, SourceGenerationContext.Default.MyPerson); } [Benchmark] public void SerializeObject() { string jsonString = JsonSerializer.Serialize(p1); } } } </pre> <br /> 실행해 보면 이런 결과가 나옵니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > | Method | Mean | Error | StdDev | Gen0 | Allocated | |---------------- |----------:|----------:|---------:|-------:|----------:| | SerializeSrcGen | 80.27 ns | 7.896 ns | 0.433 ns | 0.0061 | 96 B | // 구조체 + Source Generator를 사용한 버전 | SerializeObject | 103.30 ns | 10.666 ns | 0.585 ns | 0.0045 | 72 B | // 클래스를 전달한 버전 </pre> <br /> 보는 바와 같이 Source Generator를 사용한 버전이 역시나 빠르지만, GC Heap은 24바이트 더 사용하고 있습니다. 직렬화된 JSON 텍스트의 길이가 22 + 1, 즉 46바이트이므로 각각 50바이트/26바이트 씩을 더 쓰고 있는 것입니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 정리해 보면, "<a target='tab' href='https://www.sysnet.pe.kr/3/0/5786'>익명 클래스 말고 익명 구조체는 불가능한걸까요?</a>" 질문의 익명 구조체는 현재 C#에서 지원하지 않고 있습니다. 단지, 구조체를 직접 정의해 전달하는 것은 가능하지만 그런 경우라면 박싱이 발생하지 않도록 Source Generator를 함께 사용해야 합니다. 그 결과, 속도는 빨라지지만 (개체 풀링 및 Span의 사용에도 불구하고) GC Heap의 사용은 여전히 발생합니다.<br /> <br /> 그렇긴 한데, 어쨌든 위의 결과를 보면 0세대 GC Heap의 가비지 수집이 꽤나 최적화가 잘 되었다는 느낌은 받게 됩니다.<br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=2008&boardid=331301885'>첨부 파일은 이 글의 테스트 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
9687
(왼쪽의 숫자를 입력해야 합니다.)