Microsoft MVP성태의 닷넷 이야기
.NET Framework: 90. XmlSerializer 생성자의 실행 속도를 올리는 방법 [링크 복사], [링크+제목 복사],
조회: 29772
글쓴 사람
정성태 (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이 호출되는 경우에도 보안상의 이유로 발생할 수가 있군요. ^^
정성태

... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
12037정성태10/15/201924455.NET Framework: 867. C# - Encoding.Default 값을 바꿀 수 있을까요?파일 다운로드1
12036정성태10/14/201925578.NET Framework: 866. C# - 고성능이 필요한 환경에서 GC가 발생하지 않는 네이티브 힙 사용파일 다운로드1
12035정성태10/13/201919709개발 환경 구성: 461. C# 8.0의 #nulable 관련 특성을 .NET Framework 프로젝트에서 사용하는 방법 [2]파일 다운로드1
12034정성태10/12/201919029개발 환경 구성: 460. .NET Core 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 [1]
12033정성태10/11/201923186개발 환경 구성: 459. .NET Framework 프로젝트에서 C# 8.0/9.0 컴파일러를 사용하는 방법
12032정성태10/8/201919315.NET Framework: 865. .NET Core 2.2/3.0 웹 프로젝트를 IIS에서 호스팅(Inproc, out-of-proc)하는 방법 - AspNetCoreModuleV2 소개
12031정성태10/7/201916688오류 유형: 569. Azure Site Extension 업그레이드 시 "System.IO.IOException: There is not enough space on the disk" 예외 발생
12030정성태10/5/201923519.NET Framework: 864. .NET Conf 2019 Korea - "닷넷 17년의 변화 정리 및 닷넷 코어 3.0" 발표 자료 [1]파일 다운로드1
12029정성태9/27/201924254제니퍼 .NET: 29. Jennifersoft provides a trial promotion on its APM solution such as JENNIFER, PHP, and .NET in 2019 and shares the examples of their application.
12028정성태9/26/201919306.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도파일 다운로드1
12027정성태9/26/201914902오류 유형: 568. Consider app.config remapping of assembly "..." from Version "..." [...] to Version "..." [...] to solve conflict and get rid of warning.
12026정성태9/26/201920383.NET Framework: 862. C# - Active Directory의 LDAP 경로 및 정보 조회
12025정성태9/25/201918647제니퍼 .NET: 28. APM 솔루션 제니퍼, PHP, .NET 무료 사용 프로모션 2019 및 적용 사례 (8) [1]
12024정성태9/20/201920577.NET Framework: 861. HttpClient와 HttpClientHandler의 관계 [2]
12023정성태9/18/201921102.NET Framework: 860. ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계파일 다운로드1
12022정성태9/12/201924959개발 환경 구성: 458. C# 8.0 (Preview) 신규 문법을 위한 개발 환경 구성 [3]
12021정성태9/12/201940767도서: 시작하세요! C# 8.0 프로그래밍 [4]
12020정성태9/11/201923951VC++: 134. SYSTEMTIME 값 기준으로 특정 시간이 지났는지를 판단하는 함수
12019정성태9/11/201917544Linux: 23. .NET Core + 리눅스 환경에서 Environment.CurrentDirectory 접근 시 주의 사항
12018정성태9/11/201916337오류 유형: 567. IIS - Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. (D:\lowSite4\web.config line 11)
12017정성태9/11/201920085오류 유형: 566. 비주얼 스튜디오 - Failed to register URL "http://localhost:6879/" for site "..." application "/". Error description: Access is denied. (0x80070005)
12016정성태9/5/201920115오류 유형: 565. git fetch - warning: 'C:\ProgramData/Git/config' has a dubious owner: '(unknown)'.
12015정성태9/3/201925585개발 환경 구성: 457. 윈도우 응용 프로그램의 Socket 연결 시 time-out 시간 제어
12014정성태9/3/201919303개발 환경 구성: 456. 명령행에서 AWS, Azure 등의 원격 저장소에 파일 관리하는 방법 - cyberduck/duck 소개
12013정성태8/28/201922206개발 환경 구성: 455. 윈도우에서 (테스트) 인증서 파일 만드는 방법 [3]
12012정성태8/28/201926791.NET Framework: 859. C# - HttpListener를 이용한 HTTPS 통신 방법
... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...