본문 바로가기

.NET/C#

.NET Array는 왜 12 bytes 의 기본 메모리를 점유할까? [출처] .NET Array는 왜 12 bytes 의 기본 메모리를 점유할까?|작성자 techshare

http://blog.naver.com/techshare/100143259127

위의 링크에서 퍼온 글입니다.
 

지난 번 글을 살펴보면서, System.Char [] 개체가 기본적으로 12 바이트의 크기를 점유하는 것을 확인했습니다.

StringBuilder 에서의 OutOfMemoryException 오류 원인 분석
; http://www.sysnet.pe.kr/2/0/1171

그냥 숫자를 맞추려고 그랬던 것인지... 아니면 실제로 12 bytes를 점유하고 있는지 어디 확인해 볼까요? ^^




예제는, 지난 번 상황을 그대로 이어가겠습니다.

0:000> .loadby sos clr

0:000> !dumpheap -stat
total 0 objects
Statistics:
      MT    Count    TotalSize Class Name
79ba6524        1           12 System.Nullable`1[[System.Boolean, mscorlib]]
79ba5938        1           12 System.Collections.Generic.ObjectEqualityComparer`1[[System.Type, mscorlib]]
79ba4b44        1           12 System.Security.Permissions.ReflectionPermission
79ba0e48        1          112 System.AppDomain
... [생략] ...
79ba28b8       49         2248 System.Int32[]
79b9f92c      699        28864 System.String
79b56ba8      873        45644 System.Object[]
79b9faf8   105054      2941512 System.Text.StringBuilder
79ba1d08   105075   1681842372 System.Char[]
Total 213250 objects

우선, 그 12 bytes가 혹시 Array 자체가 소유한 인스턴스 필드 때문에 발생한 것이 아닐까요? 이를 확인하려면 .NET Reflector 를 통해서 추적하는 것이 가능하지만, 기왕에 windbg 명령어를 익힐 겸 Method Table 주소에서 찾아가는 방법을 설명해 보겠습니다.

위의 "dumpheap" 결과에서 출력된 "System.Char[]" 의 "MT(Method Table)" 값을 이용하여 "EEClass"를 알아낼 수 있습니다. EEClass는 .NET Reflection 의 Type 정보와 유사하다고 생각하시면 됩니다.

0:000> !dumpmt 79ba1d08   
EEClass:      798d9878
Module:       79881000
Name:         System.Char[]
mdToken:      02000000
File:         C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
BaseSize:        0xc
ComponentSize:   0x2
Slots in VTable: 28
Number of IFaces in IFaceMap: 6

BaseSize == 0xc (12) 로 설정된 것으로 보아 "System.Char[]" 개체 하나에 12 바이트를 소비하는 것은 맞는 것 같습니다. 이제 클래스 자체를 검사해 보면,

0:000> !DumpClass 798d9878
Class Name:      System.Char[]
mdToken:         02000000
File:            C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Parent Class:    798d8ad8
Module:          79881000
Method Table:    79ba1d08
Vtable Slots:    18
Total Method Slots:  1c
Class Attributes:    2101  
Transparency:        Transparent
NumInstanceFields:   0
NumStaticFields:     0

보시는 바와 같이 Instance Fields 가 0 이므로, 그 자체의 메모리 소비는 없습니다. 그럼, 혹시 상속받은 것이 아닐까요? 이를 알아보기 위해 "Parent Class"를 다시 찾아보면,

0:000> !DumpClass 798d8ad8
Class Name:      System.Array
mdToken:         02000031
File:            C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Parent Class:    79883ef8
Module:          79881000
Method Table:    79b9f75c
Vtable Slots:    18
Total Method Slots:  3b
Class Attributes:    102081  Abstract, 
Transparency:        Transparent
NumInstanceFields:   0
NumStaticFields:     0

아하~~~ 익히 알고 있던 데로 "System.Char[]" 개체가 System.Array 를 상속받아 처리된 것이군요. 게다가 System.Array 역시 Instance Fields == 0 이고, 다시 한번 상위 클래스로 이동해 보겠습니다.

0:000> !DumpClass 79883ef8
Class Name:      System.Object
mdToken:         02000002
File:            C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Parent Class:    00000000
Module:          79881000
Method Table:    79b9f568
Vtable Slots:    4
Total Method Slots:  a
Class Attributes:    102001  
Transparency:        Transparent
NumInstanceFields:   0
NumStaticFields:     0

System.Object 까지 거슬러 왔고, Parent Class == 00000000 인 것으로 보아 최상위 개체입니다. 물론, Instance Fields == 0 이므로 역시 자체적으로 할당된 메모리는 없습니다.




12 바이트 영역에는 그럼 어떤 값들이 채워져 있을까요? 이를 확인하기 위해 메모리의 값을 쉽게 판단할 수 있는 '문자열'을 선택해보겠습니다.

0:000> !dumpheap -mt 79ba1d08 <== 값 79ba1d08 은 "System.Char []" 의 MT 값
 Address       MT     Size
...[생략]...
7e106c78 79ba1d08       24     
7e106e8c 79ba1d08       24     
7e10706c 79ba1d08       24     
7e107694 79ba1d08      524     
7e1078f0 79ba1d08       44     
7e107938 79ba1d08       44     
7e107b7c 79ba1d08      272     
7e108260 79ba1d08      272     
7e108884 79ba1d08      100     
7e108934 79ba1d08      100     
7e108e08 79ba1d08      156     
7e1090ac 79ba1d08       16     
7e1090d8 79ba1d08      524     
7e109558 79ba1d08       12     
7e109564 79ba1d08     1588     
7e109bb0 79ba1d08       16     
7e109bc0 79ba1d08      176     
total 0 objects
Statistics:
      MT    Count    TotalSize Class Name
79ba1d08   105213   1684052028 System.Char[]
Total 105213 objects

오호... 마침 12 바이트 짜리가 눈에 띄는데요. do(DumpObject) 명령어를 내려서 살펴보면,

0:000> !do 7e109558
Name:        System.Char[]
MethodTable: 79ba1d08
EEClass:     798d9878
Size:        12(0xc) bytes
Array:       Rank 1, Number of elements 0, Type Char
Element Type:System.Char
Content:     
Fields:
None

요소가 하나도 없는데도 12 바이트를 차지하고 있으니, 다시 한번 증명이 되고 있습니다. 그 다음, 44 바이트를 점유하고 있는 문자열을 선택해 볼까요? 계산대로라면 (44 - 12) / 2 (unicode) = 16 글자를 포함하고 있을 텐데요. DumpObject 역시 동일하게 결과를 출력해 주고 있습니다.

0:000> !do 7e1078f0
Name:        System.Char[]
MethodTable: 79ba1d08
EEClass:     798d9878
Size:        44(0x2c) bytes
Array:       Rank 1, Number of elements 16, Type Char
Element Type:System.Char
Content:     mscorlib.resourc
Fields:
None

나아가서, DumpObject 명령어로 정제된 출력결과가 아닌 메모리 상의 Raw 데이터를 한번 확인해 보겠습니다. 이를 위해 windbg 의 "View" / "Memory (Alt+5)" 를 선택해서 직접 Object 의 주소 값을 입력해 44 바이트 까지의 값을 확인해 보면 다음과 같이 나옵니다.

dump_array_1.png

7e1078f0 08 1d ba 79 10 00 00 00 6d 00 73 00 63 00 6f 00 72 00 6c 00 69 00 62  ...y....m.s.c.o.r.l.i.b
7e107907 00 2e 00 72 00 65 00 73 00 6f 00 75 00 72 00 63 00 00 00 00 00        ...r.e.s.o.u.r.c.....

색상별로 분리하면 "mscorlib.resourc" 문자열에 해당하는 값을 제외하고 앞단에 8바이트, 뒷단에 4바이트가 배치된 것을 알 수 있습니다.

08 1d ba 79 10 00 00 00   ...y....
6d 00 73 00 63 00 6f 00   72 00 6c 00 69 00 62 00 2e 00 72 00 65 00 73 00 6f 00 75 00 72 00 63 00    m.s.c.o.r.l.i.b...r.e.s.o.u.r.c
00 00 00 00               ....

부가적인 바이트들을 4 바이트로 나눠서 살펴보면 2개 정도는 의미가 드러납니다.

08 1d ba 79 ==> 0x79ba1d08 (MethodTable)
10 00 00 00 ==> 0x00000010 (배열 요소 크기?)
나머지 32 바이트는 문자열
00 00 00 00 ==> 0x00000000 (?)

0x79ba1d08 값은 워낙 특정하다 보니 MethodTable 값과 일치하는 것을 우연이라고 보기에는 어렵겠죠? 반면에 문자열 크기라고 계산된 0x00000010 값은 왠지 우연의 일치일 수 있으므로 다른 Char 배열을 하나 더 선정해서 확인해 보는 것이 좋겠습니다.

0:000> !do 7e10706c
Name:        System.Char[]
MethodTable: 79ba1d08
EEClass:     798d9878
Size:        22(0x16) bytes
Array:       Rank 1, Number of elements 5, Type Char
Element Type:System.Char
Content:     en-us
Fields:
None

7e10706c 08 1d ba 79 05 00 00 00 65 00 6e 00 2d 00 75 00 73 00 00 00 00 00  ...y....e.n.-.u.s.....

08 1d ba 79 ==> 0x79ba1d08 (MethodTable)
05 00 00 00 ==> 0x00000005 (5글자: 배열 요소 크기)
65 00 6e 00 2d 00 75 00 73 00 ==> e.n.-.u.s.
00 00 00 00 ==> 0x000000 (?)

아하... 이 정도면 확정적이군요. 그렇다면, 마지막의 "0x00000000" 4바이트 값은 무엇일까요? 모릅니다. ^^; 이에 대한 설명은 (아쉽게도 제가 검색한 문서 내에서는) 찾을 수 없었습니다. (아마도 reserved 가 아닐까요? ^^)




배열이라고 해서 모두 12 bytes 값이 점유되는 것은 아닙니다. 일례로 지난 번에 살펴 본 ".NET 타입에 대한 배열"의 경우에는 기본적으로 16 bytes 값을 소비합니다. 아래는, 직접 확인하기 위해 ConsoleApplication1.Program [] 에 대해 시도한 처리 결과를 보여주고 있습니다.

0:004> .loadby sos clr

0:004> ~0s
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll - 
eax=00000000 ebx=00000001 ecx=00000000 edx=00000000 esi=002dedf4 edi=00000000
eip=7762fd81 esp=002dedb0 ebp=002dee18 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
ntdll!NtDelayExecution+0x15:
7762fd81 83c404          add     esp,4

0:000> !dso
PDB symbol for clr.dll not loaded
OS Thread Id: 0x1b2c (0)
ESP/REG  Object   Name
002DEF28 0254bf90 System.Object[]    (ConsoleApplication1.Program[])
002DEF2C 0254bf90 System.Object[]    (ConsoleApplication1.Program[])
002DEF30 0254bf80 System.Object[]    (System.String[])
002DEFE4 0254bf80 System.Object[]    (System.String[])
002DF184 0254bf80 System.Object[]    (System.String[])
002DF1B8 0254bf80 System.Object[]    (System.String[])

0:000> !do 0254bf90 
Name:        System.Object[]
MethodTable: 72f86ba8
EEClass:     72d09688
Size:        16(0x10) bytes
Array:       Rank 1, Number of elements 0, Type CLASS
Element Type:ConsoleApplication1.Program
Fields:
None

0:000> dd 0254bf90 
0254bf90  72f86ba8 00000000 00193810 00000000
0254bfa0  00000000 00000000 00000000 00000000
0254bfb0  00000000 00000000 00000000 00000000
0254bfc0  00000000 00000000 00000000 00000000
0254bfd0  00000000 00000000 00000000 00000000
0254bfe0  00000000 00000000 00000000 00000000
0254bff0  00000000 00000000 00000000 00000000
0254c000  00000000 00000000 00000000 00000000

보시는 것처럼, 기본 점유 공간이 16 바이트가 되는데요. 값의 의미는 다음과 같습니다.

72f86ba8: System.Object [] 형에 대한 MethodTable 값
00000000: 배열의 요소 수
00193810: ConsoleApplication.Program 타입에 대한 MethodTable 값
00000000: {unknown}

즉, 배열 자체의 타입은 System.Object[] 이지만 내부에 저장될 요소 - "Element Type" 정보도 함께 보관하고 있는 것입니다.