First of all, a small disclaimer before the actual question:
I know there are a lot of closed/duplicate questions regarding the difference between the
sizeof
operator and theMarshal.SizeOf<T>
method, and I do understand the difference between the two. Here I'm talking about theSizeOf<T>
method in the newUnsafe
class
So, I'm not sure I understand the actual difference between these two operations, and whether there's a specific difference when using the method on a struct/class in particular.
The sizeof
operator takes a Type name and returns the number of managed bytes it is supposed to take up when allocated (ie. an Int32
will return 4, for example).
The Unsafe.SizeOf<T>
method on the other hand, is implemented in IL like all the other methods in the Unsafe
class, and looking at the code here's what it does:
.method public hidebysig static int32 SizeOf<T>() cil managed aggressiveinlining
{
.custom instance void System.Runtime.Versioning.NonVersionableAttribute::.ctor() = ( 01 00 00 00 )
.maxstack 1
sizeof !!T
ret
}
Now, if I'm not wrong, the code is just calling sizeof !!T
which is the same as sizeof(T)
(calling the sizeof
operator with the type name T
), so wouldn't the two of them be exactly equivalent?
Also, I see the method is also allocating a useless object (the NonVersionableAttribute
) in the first line, so wouldn't that cause a small amount of memory to be heap-allocated as well?
My question is:
Is it safe to say that the two methods are perfectly equivalent and that therefore it is just better to use the classic
sizeof
operator, as that also avoid the allocation of that attribute in theSizeOf<T>
method? Was thisSizeOf<T>
method added to theUnsafe
class just for convenience at this point?
.custom
statement just tells you that there is a custom-attribute present belonging to this method. As custom-attributes are just metadata they are not involved in a regular method call. – Hamitosemitic