开发者

How to calculate the size of a struct instance?

开发者 https://www.devze.com 2023-03-16 08:49 出处:网络
This question is simply to satisfy my interest. Reading Choosing Between Classes and Structures the page says \"It has an instance size smaller than 16 bytes.\".

This question is simply to satisfy my interest. Reading Choosing Between Classes and Structures the page says "It has an instance size smaller than 16 bytes.".

Given this simple immutable struct.

public struct Coordinate
{
    private readonly double 开发者_StackOverflow_latitude;
    private readonly double _longitude;

    public Coordinate(double latitude, double longitude)
    {
        _latitude = latitude;
        _longitude = longitude;
    }

    public double Latitude
    {
        get { return _latitude; }
    }

    public double Longitude
    {
        get { return _longitude; }
    }
}

Do properties also count towards the 16 byte limit? Or do only fields count?

If the latter wouldn't using a struct fail the guidelines provided by Microsoft since a double is 8 bytes? Two doubles would be 16 bytes which is exactly 16 bytes and not less.


Just the fields count.

So in this case you've got two 64-bit (8 byte) fields; you're just about within the bounds of your heuristic.

Note that if you use any auto-implemented properties then the compiler will create "hidden" fields to back those properties, so your overall sum should take those into account too.

For example, this struct also requires 16 bytes:

public struct Coordinate
{
    public Coordinate(double latitude, double longitude) : this()
    {
        Latitude = latitude;
        Longitude = longitude;
    }

    public double Latitude { get; private set; }
    public double Longitude { get; private set; }
}


First, to determine the size of your struct, use Marshal.SizeOf(struct) which returns the sum of the sizes of its members. Microsoft does recommend that the size of a struct be below 16 bytes, but it is really up to you. There is some overhead associated with structs. In case your struct has reference types as members, make sure you don't include the size of instances of reference types, just the size of the references.


You can find out the size using

System.Runtime.InteropServices.Marshal.SizeOf(new Coordinate());

Which returns 16. You are right - only fields count. You can add properties without increasing the size.


You can use sizeof( Coordinate ) to calculate it progamatically, although this will require unsafe context. In your case the size is 16 bytes as you said. Properties do not count towards the size, since they are only wrappers. The size of a structure is simply the sum of the sizes of all its fields.

0

精彩评论

暂无评论...
验证码 换一张
取 消