Microsoft MVP성태의 닷넷 이야기
.NET Framework: 90. XmlSerializer 생성자의 실행 속도를 올리는 방법 [링크 복사], [링크+제목 복사],
조회: 29567
글쓴 사람
정성태 (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)
13667정성태7/7/20246625닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20247714Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20247895Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20247504닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20247500닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20247425Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20247538오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20247875개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20248265개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20247925닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20248115Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20247875닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20247796오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20247939닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20249259닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20248498닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20248421개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20247980오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20248306오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20249348개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20247781오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20248210개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20248870닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20248335오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20248221스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20248684Linux: 71. Ubuntu 20.04를 22.04로 업데이트
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...