Microsoft MVP성태의 닷넷 이야기
.NET Framework: 90. XmlSerializer 생성자의 실행 속도를 올리는 방법 [링크 복사], [링크+제목 복사],
조회: 24210
글쓴 사람
정성태 (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)
13492정성태12/19/20232465개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232293Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232436개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232198개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232163오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232475개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232289개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232154오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232280개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232399닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20233100닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232397개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232786개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232419개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232653닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232389닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232470닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232285개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232571닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232282C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232394Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232725닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232513닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232371닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232508오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232666닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...