在C#计算类型大小

起因

在C#计算类型大小,有3种(我知道的),分别为:Marshal.SizeOf<T>()和Unsafe.SizeOf<T>()及sizeof.
在C#中获取类型在内存中分配大小的几种方式

注意事项

这3种方式使用顺序为: sizeof > Unsafe.SizeOf<T> > Marshal.SizeOf<T>()
反编译工具这里使用的是DnSpy,没有使用ILSpy,是因为DnSpy可以直接进行断点调试.

测试代码:
int valSize = sizeof(int);    //计算基本类型大小(在编译时,就确定类型大小)
Console.WriteLine(valSize);  

Console.WriteLine(Marshal.SizeOf<int>());

Console.WriteLine(Unsafe.SizeOf<int>());

反编译代码为:

int valSize = 4;   //从反编译的代码,看到这里已经类型的大小
Console.WriteLine(valSize);
Console.WriteLine(Marshal.SizeOf<int>());
Console.WriteLine(Unsafe.SizeOf<int>());

接着看Marshal.Sizeof<T>()的代码:

//1. 在内部,获取泛型类型的信息
public static int SizeOf<T>()
{
    return Marshal.SizeOf(typeof(T));
}

//2. 根据类型信息
public static int SizeOf(Type t)
{
    if (t == null)
    {
        throw new ArgumentNullException("t");
    }
    if (!t.IsRuntimeImplemented())
    {
        throw new ArgumentException(SR.Argument_MustBeRuntimeType, "t");
    }
    if (t.IsGenericType)
    {
        throw new ArgumentException(SR.Argument_NeedNonGenericType, "t");
    }
    return Marshal.SizeOfHelper(t, true);
}

//3. 根据类型信息,(这里调用c/cpp实现的函数,应该是CLR中的函数)从CLR获取该类型的大小
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable);

最后看UnSafe.Size<T>的代码:

[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int SizeOf<T>()
{
    return sizeof(T);   //竟然是用sizeof,好神奇
}

那吗? 在测试的代码中Unsafe.SizeOf<int>()为什么没有像sizeof(int)在编译后,变为常量4呢?那么我们去看UnSafe的源码,去看看里面有什么神奇的?

[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int SizeOf<T>()
{
    // This method is implemented by the toolchain
    throw new PlatformNotSupportedException();

    // sizeof !!0      
    // ret
}

在方法代码中,没有具体的实现,这和我们在看DnSpy看的代码不一致呀! 不过在代码中有IL注释,那么我们去看看DnSpy中的SizeOf的IL代码是什么样的?

// Token: 0x0600000B RID: 11 RVA: 0x00002960 File Offset: 0x00000D60
.method public hidebysig static
    int32 SizeOf<T>() cil managed aggressiveinlining 
{
	.custom instance void System.Runtime.Versioning.NonVersionableAttribute::.ctor() = (
		01 00 00 00
	)
	// Header Size: 12 bytes
	// Code Size: 7 (0x7) bytes
	.maxstack 1

	/* 0x00000D6C FE1C0100001B */ IL_0000: sizeof    !!T
    /* 0x00000D72 2A           */     IL_0006: ret
} // end of method Unsafe::SizeOf

对比源码和反编译代码,发现UnSafe.SizeOf是编译的时候,调用sizeof对类型计算大小.至于为什么没有和直接调用sizeof一样,会在下边得出结果.

性能对比和生成汇编代码对比

在这里使用Benchmark.DotNet进行性能对比和生成汇编代码对比. .Net版本为.Net 6 预览2
[MemoryDiagnoser]
[DisassemblyDiagnoser]
public class SizeOfTest
{
    [Benchmark]
    public void SizeOf()
    {
        for (int i = 0; i < 10000000; i++)
        {
            int size = sizeof(int);
            if (size > 0)
            {

            }
        }
    }

    [Benchmark]
    public void UnSafeSizeOf()
    {
        for (int i = 0; i < 10000000; i++)
        {
            int size = Unsafe.SizeOf<int>();
            if (size > 0)
            {

            }
        }
    }

    [Benchmark]
    public void MarshalSizeOf()
    {
        for (int i = 0; i < 10000000; i++)
        {
            int size = Marshal.SizeOf<int>();
            if (size > 0)
            {

            }
        }
    }
}
使用Benchmark.DotNet分别对sizeof/UnSafe.SizeOf/Marshal.SizeOf进行对比
下面看通过Benchmark.DotNet对测试方法,生成的汇编代码:
; dotnet_perf.SizeOfTest.SizeOf()
       xor       eax,eax
M00_L00:
       inc       eax
       cmp       eax,989680
       jl        short M00_L00
       ret
; Total bytes of code 12

; dotnet_perf.SizeOfTest.UnSafeSizeOf()
       xor       eax,eax
M00_L00:
       inc       eax
       cmp       eax,989680
       jl        short M00_L00
       ret
; Total bytes of code 12


; dotnet_perf.SizeOfTest.MarshalSizeOf()
       push      rdi
       push      rsi
       sub       rsp,28
       xor       esi,esi
       mov       rcx,offset MT_System.Int32
       call      CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE
       mov       rdi,rax
M00_L00:
       mov       rcx,rdi
       call      System.Runtime.InteropServices.Marshal.SizeOf(System.Type)
       inc       esi
       cmp       esi,989680
       jl        short M00_L00
       add       rsp,28
       pop       rsi
       pop       rdi
       ret
; Total bytes of code 51
; System.Runtime.InteropServices.Marshal.SizeOf(System.Type)
       push      rdi
       push      rsi
       sub       rsp,28
       mov       rsi,rcx
       test      rsi,rsi
       je        near ptr M01_L02
       mov       rcx,offset MT_System.RuntimeType
       cmp       [rsi],rcx
       jne       short M01_L00
       mov       rcx,rsi
       mov       rax,[rsi]
       mov       rax,[rax+60]
       call      qword ptr [rax+10]
       test      eax,eax
       jne       short M01_L01
       mov       rcx,rsi
       mov       edx,1
       add       rsp,28
       pop       rsi
       pop       rdi
       jmp       near ptr System.Runtime.InteropServices.Marshal.SizeOfHelper(System.Type, Boolean)
M01_L00:
       mov       rcx,offset MT_System.ArgumentException
       call      CORINFO_HELP_NEWFAST
       mov       rsi,rax
       mov       ecx,7EC1
       mov       rdx,7FFA0A6C4020
       call      CORINFO_HELP_STRCNS
       mov       rcx,rax
       xor       edx,edx
       call      System.SR.GetResourceString(System.String, System.String)
       mov       rdi,rax
       mov       ecx,208C
       mov       rdx,7FFA0A6C4020
       call      CORINFO_HELP_STRCNS
       mov       r8,rax
       mov       rdx,rdi
       mov       rcx,rsi
       call      System.ArgumentException..ctor(System.String, System.String)
       mov       rcx,rsi
       call      CORINFO_HELP_THROW
M01_L01:
       mov       rcx,offset MT_System.ArgumentException
       call      CORINFO_HELP_NEWFAST
       mov       rsi,rax
       mov       ecx,805D
       mov       rdx,7FFA0A6C4020
       call      CORINFO_HELP_STRCNS
       mov       rcx,rax
       xor       edx,edx
       call      System.SR.GetResourceString(System.String, System.String)
       mov       rdi,rax
       mov       ecx,208C
       mov       rdx,7FFA0A6C4020
       call      CORINFO_HELP_STRCNS
       mov       r8,rax
       mov       rdx,rdi
       mov       rcx,rsi
       call      System.ArgumentException..ctor(System.String, System.String)
       mov       rcx,rsi
       call      CORINFO_HELP_THROW
M01_L02:
       mov       rcx,offset MT_System.ArgumentNullException
       call      CORINFO_HELP_NEWFAST
       mov       rsi,rax
       mov       ecx,208C
       mov       rdx,7FFA0A6C4020
       call      CORINFO_HELP_STRCNS
       mov       rdx,rax
       mov       rcx,rsi
       call      System.ArgumentNullException..ctor(System.String)
       mov       rcx,rsi
       call      CORINFO_HELP_THROW
       int       3
; Total bytes of code 313

从sizeof和UnSafe.SizeOf汇编代码对比,发现sizeof和UnSafe.SizeOf是一样的.至于在反编译的时候,看的结果为什么不一样?sizeof是编译时是由编译器计算出的,而UnSafe.SizeOf是JIT在运行时计算出的.

秋风 2021-03-28