How do I check the number of bytes consumed by a structure?
You can use either the sizeof
operator or SizeOf
function.
There are some differences between those options, see the reference links for more.
Anyway a good way to use that function is to have a generic method or extension method like these:
static class Test
{
static void Main()
{
//This will return the memory usage size for type Int32:
int size = SizeOf<Int32>();
//This will return the memory usage size of the variable 'size':
//Both lines are basically equal, the first one makes use of ex. methods
size = size.GetSize();
size = GetSize(size);
}
public static int SizeOf<T>()
{
return System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
}
public static int GetSize(this object obj)
{
return System.Runtime.InteropServices.Marshal.SizeOf(obj);
}
}
finding out memory consumption of a structure
You're looking for the sizeof operator
Returns size in bytes of the object representation of type
Example usage:
#include <iostream>
class tnode;
struct tNode {
short data;
tnode *left;
tnode *right;
tnode *student;
};
int main()
{
std::cout << sizeof(tNode) << std::endl;
return 0;
}
Output on my machine:
32
How can I properly calculate the size of a struct array? Am I doing this right?
This line:
printf("total size of structure is %d\n", allocation);
Is incorrect as allocation
is a pointer. To get the total size simply do the following:
#include <stdio.h>
#define MAX 50 //for structure
struct address{
int zip; // 4 bytes
char name[20]; // 20 bytes
char street[40]; // 40 bytes
char city[16]; // 16 bytes
char state[4]; // 4 bytes
char country[10]; // 10 bytes
};
int main()
{
struct address addr[MAX];
printf("Size %zu\n", sizeof(addr));
return 0;
}
How to calculate the number of bytes stored in object
You're seeing the evidence of otherwise-"invisible" padding bytes that the compiler has added (in this case, to the end of your class) to achieve alignment.
Compilers like to align structures on convenient (e.g. 64 bits, or 8 bytes, in your case) boundaries for more efficient access to their members. This is true in this case if you were to create an array of multiple Foo
objects; the end padding would keep the start of each one on an 8-byte (64-bit) boundary. If you had varying sizes of fields within this class, you might also see additional padding between the fields for the same purpose.
How to calculate how big a struct or class is?
Only non-static variables use up space, methods don't. For example, your struct that you made there is four bytes big, because it is the size of an int.
You can also calculate the size using Marshal.SizeOf(GetType((Struct1)).
Unless you have memory critical applications, or have some special reasons you need a struct, I would suggest always using a class.
How to calculate the size of a struct instance?
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; }
}
Structure size not reflecting correct number of bytes in C#
The mem2
field has no MarshalAs
attribute and so uses default marshalling. And that is as pointer to the first element.
You probably meant to write:
public struct champ
{
public uint mem1;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 15)]
public byte[] mem2;
public champ(int x) { ... }
}
The size of the struct will be 20 because alignment rules mean that an extra padding byte is added at the end of the struct. That is needed to ensure that the size of the struct is an exact multiple of 4, the size of uint
. This ensures that arrays of the struct will properly align mem1
.
How to find number of bytes taken by python variable
You can find the functionality you are looking for here (in sys.getsizeof
- Python 2.6 and up).
Also: don't shadow the int
builtin!
import sys
myint = 12
print(sys.getsizeof(myint))
Related Topics
Reflection to Identify Extension Methods
How to Show the "Paste JSON Class" in Visual Studio 2012 When Clicking on Paste Special
Find Size of Object Instance in Bytes in C#
How to Set a Property Value with Reflection
How to Get .Net Core Projects to Copy Nuget References to the Build Output
Oledbcommand Parameters Order and Priority
Implementing Idisposable Correctly
Calling C# Code from C++, But Executeindefaultappdomain() Is Too Limited
Blazor - Display Wait or Spinner on API Call
Reading PDF Content with Itextsharp Dll in Vb.Net or C#
How to Convert a Gi-Normous Integer (In String Format) to Hex Format? (C#)
When to Dispose Cancellationtokensource
How to Animate a Line on a Canvas in C#
Using Stringwriter for Xml Serialization
How to Decode a Url Parameter Using C#
Weird Error Upgrading ASP.NET MVC from 4 to 5
Why Should I Prefer Single 'Await Task.Whenall' Over Multiple Awaits