Microsoft MVP성태의 닷넷 이야기
.NET Framework: 90. XmlSerializer 생성자의 실행 속도를 올리는 방법 [링크 복사], [링크+제목 복사]
조회: 24152
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 9개 있습니다.)
.NET Framework: 90. XmlSerializer 생성자의 실행 속도를 올리는 방법
; https://www.sysnet.pe.kr/2/0/511

.NET Framework: 92. XmlSerializer 생성자의 실행 속도를 올리는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/521

.NET Framework: 100. XML Serializer를 이용한 값 복사
; https://www.sysnet.pe.kr/2/0/577

.NET Framework: 122. XML Serializer를 이용한 값 복사: 성능은 어떨까!
; https://www.sysnet.pe.kr/2/0/653

.NET Framework: 648. Dictionary<TKey, TValue>를 deep copy하는 방법
; https://www.sysnet.pe.kr/2/0/11157

.NET Framework: 660. Shallow Copy와 Deep Copy
; https://www.sysnet.pe.kr/2/0/11220

.NET Framework: 1141. XmlSerializer와 Dictionary 타입
; https://www.sysnet.pe.kr/2/0/12942

.NET Framework: 2078. .NET Core/5+를 위한 SGen(Microsoft.XmlSerializer.Generator) 사용법
; https://www.sysnet.pe.kr/2/0/13196

.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?
; https://www.sysnet.pe.kr/2/0/13198





XmlSerializer 생성자의 실행 속도를 올리는 방법


지금쯤이면 이미 많은 분들이 아시는 내용이겠지만. 그래도 한번 정리를 해보고 지나가야 할 내용 같아서 써봅니다.

XmlSerializer 생성자에 타입을 전달하는 코드가 처음 실행될 때, 생성자안에서는 타입에 해당하는 직렬화 코드가 이미 있는지를 먼저 찾아보게 됩니다. 만약 없다면, 새롭게 해당 클래스를 직렬화하는 코드를 동적으로 생성해서 로드하게 됩니다.

왜냐하면, 직렬화를 위해서는 반드시 해당 클래스를 일일이 "Reflection"을 통해서 조사해야 하는데, 여기에서 오는 속도 저하가 심각하기 때문에, 아예 처음 한번은 Reflection을 이용해서 직렬화를 해주는 동적 코드를 생성하는 것으로 이 문제를 해결하고 있습니다.

어디... 눈으로 한번 확인해 볼까요?

우선, VS.NET의 "도구" / "옵션" 창에서 "Enable Just My Code" 옵션을 해제하십시오.

그런 다음, 아래와 같은 코드를 작성해서 빌드한 후, 굵은 글씨로 되어 있는 부분에 BP(Break Point)를 설정한 후 "F5" 디버깅 모드로 실행시켜 보십시오.

public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e)
  {
    MyClass myClass = new MyClass();
    XmlSerializer xs = new XmlSerializer(typeof(MyClass)); // BP(Break Point) 설정
  }
}

public class MyClass
{
  public string Prop;
}

"F10" 키를 눌러서 라인을 실행시키면, VS.NET의 "Output" 창에는 다음과 같은 내용이 출력되는 것을 확인할 수 있습니다.

A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
'XmlSerializerTest.vshost.exe' (Managed): Loaded '7ptbpl3m', No symbols loaded.

지난 회를 통해서, 우리는 "first chance exception"이 무엇인지 이미 설명을 드렸으니... 이젠 낯설지 않으시죠? ^^

그런데,,, 그냥 호기심 삼아서 위의 예외가 언제 발생하는지 추적해 볼까요?
소스 코드가 없다면 좀 단계가 어렵지만, 마이크로소프트에서 공개하고 있는 "Shared Source CLR"의 XmlSerializer 소스를 살펴보면 그 호기심을 쉽게 풀수가 있습니다.

Shared Source Common Language Infrastructure Archive
; https://github.com/SSCLI

다운로드 받아서, 아래와 같이 XmlSerializer 생성자를 살펴보면 다음과 같은 소스 코드를 확인할 수 있습니다.

.\fx\src\xml\system\xml\serialization\xmlserializer.cs
; https://github.com/SSCLI/sscli20_20060311/blob/master/fx/src/xml/system/xml/serialization/xmlserializer.cs

public XmlSerializer(Type type, string defaultNamespace) {
  if (type == null)
    throw new ArgumentNullException("type");
  this.mapping = GetKnownMapping(type, defaultNamespace);
  if (this.mapping != null) {
    this.primitiveType = type;
    return;
  }
  tempAssembly = cache[defaultNamespace, type];
  if (tempAssembly == null) {
    lock (cache) {
      tempAssembly = cache[defaultNamespace, type];
      if (tempAssembly == null) {
        XmlSerializerImplementation contract;
        Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract);
        if (assembly == null) {

cache에 없으니, TempAssembly.LoadGeneratedAssembly를 이용해서, 관련 직렬화 클래스를 로드해 봅니다. 만약 이때 로드가 안되면(assembly == null) 이후에 동적으로 생성하는 코드가 이어지는데, 여기서는 생략하고 예외가 발생하는 LoadGeneratedAssembly 메서드를 좀 더 추적해 보도록 하겠습니다.

.\fx\src\xml\system\xml\serialization\compilation.cs
; https://github.com/SSCLI/sscli20_20060311/blob/master/fx/src/xml/system/xml/serialization/compilation.cs

internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
{
  Assembly serializer = null;
  contract = null;
  string serializerName = null;
  bool logEnabled = DiagnosticsSwitches.PregenEventLog.Enabled;

  // check to see if we loading explicit pre-generated assembly
  object[] attrs = type.GetCustomAttributes(typeof(XmlSerializerAssemblyAttribute), false);
  if (attrs.Length == 0)
  {
    // Guess serializer name: if parent assembly signed use strong name 
    AssemblyName name = GetName(type.Assembly, true);
    serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
    // use strong name 
    name.Name = serializerName;
    name.CodeBase = null;
    name.CultureInfo = CultureInfo.InvariantCulture;
    try
    {
      serializer = Assembly.Load(name);
    }
    catch (Exception e)
    {
      if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
      {
        throw;
      }
      byte[] token = name.GetPublicKeyToken();
      if (token != null && token.Length > 0)
      {
        // the parent assembly was signed, so do not try to LoadWithPartialName
        return null;
      }
#pragma warning disable 618
      serializer = Assembly.LoadWithPartialName(serializerName, null);
#pragma warning restore 618

아하, 이 코드들을 보니 답이 나왔군요. ^^ Assembly.Load에서 "first-chance exception(System.IO.FileNotFoundException)"이 한번 발생하고, 이후에 Assembly.LoadWithPartialName에서 다시 한번 내부적으로 "first-chance exception(System.IO.FileNotFoundException)"이 발생하고 있습니다.




이렇게 XmlSerializer의 생성자에 전달되는 Type 하나 당 2번의 예외가 발생합니다. 한 두번 정도야 상관없겠지만, 알게 모르게 참조하는 DLL들 내부에서 이런 초기 예외가 빈번하게 발생하게 되면 눈에 띄는 실행속도 저하가 발생할 수 있습니다. (물론, 일단 한번 cache가 된다면 그 이후에는 빠르게 로드가 되지만.)

그런데, 도대체 어떤 이름의 파일을 로드하려고 시도했던 것일까요? ^^ 해답을 찾을 수 있는 방법을 이미 지난번에 다뤄보았던 "First-Chance Exception" 토픽에서 설명해 놓았으니 이 부분은 건너뛰도록 하겟습니다.

자... 그럼 이 문제를 해결하려면 어떻게 해야 할까요?

간단합니다. ^^ System.IO.FileNotFoundException이 발생하지 않도록 직렬화 관련 클래스를 미리 생성시켜 두면 됩니다. 바로 이런 목적을 위해 "sgen.exe" 파일이 제공되고 있습니다.

XmlSerializer 생성자에 전달되는 Type이 포함된 Assembly 파일을 인자로 전달하면 되는데, 만약 위의 예제 코드에서 "MyClass" 타입이 포함된 Assembly 파일명이 "ClassLibrary1.dll"이라면 다음과 같이 실행해 줄 수 있습니다.

C:\XmlSerializerTest\bin\Debug>sgen ClassLibrary1.dll
Microsoft (R) Xml Serialization support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Serialization Assembly Name: ClassLibrary1.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
Generated serialization assembly for assembly C:\XmlSerializerTest\bin\Debug\classlibrary1.dll 
  --> 'C:\XmlSerializerTest\bin\Debug\ClassLibrary1.XmlSerializers.dll'.

C:\XmlSerializerTest\bin\Debug>

자, 이제 다시 한번 "F5" 키를 눌러서 디버깅 모드로 진입하면 이번에는 "first-chance exception"이 전혀 발생하지 않습니다.




끝으로 읽을 거리 하나 제시하고 마치겠습니다. ^^

Avoid UAC prompt in IE component 
; http://blogs.msdn.com/carloc/archive/2007/06/22/avoid-uac-prompt-in-ie-component.aspx
; https://www.cloudnotes.io/avoid-uac-prompt-in-ie-component/

비스타 환경에서의 스마트 클라이언트 구동에 있어서 XmlSerializer와 관련한 재미있는 문제들이 지적되고 있습니다.



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







[최초 등록일: ]
[최종 수정일: 12/15/2022]

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

비밀번호

댓글 작성자
 



2008-02-23 05시33분
XmlSerializer 생성자의 실행 속도를 올리는 방법 - 두 번째 이야기
; http://www.sysnet.pe.kr/2/0/521
kevin25
2011-06-23 10시34분
Could not find the file 'C:\WINDOWS\TEMP\<XML serializer(Random generated file name)>.dll
; (broken) http://blogs.msdn.com/b/asiatech/archive/2010/08/02/could-not-find-the-file-c-windows-temp-lt-xml-serializer-random-generated-file-name-gt-dll.aspx

전혀 별개의 문제이긴 하지만, AllocConsole이 호출되는 경우에도 보안상의 이유로 발생할 수가 있군요. ^^
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13606정성태4/24/202444닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024312닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024321오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024502닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024787닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024836닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024845닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024861닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024882닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024855닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241049닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241050닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241068닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241079닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241217C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241193닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241150닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241262닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241168오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241324Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241111Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241060개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241194Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241453Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...