How are byte variables stored in memory?

I am reading a book about C # ( Pro C # and the .NET 4 platform from Andrew Troelsen ), and I just read this point:

Changing the base type of an enumeration can be useful if you are creating a .NET application that is deployed on a device with small memory (for example, a cell phone with .NET or PDA support) and you need to save memory where possible.

Is it true that bytes use less memory? Are they stored in 4 bytes for performance reasons? I remember how I read the last, but I can not find any information about this, even in the C # specification.

+6
c # memory byte
source share
4 answers

It is not simple. Like variables in a method, they are almost the same as int , so 4 bytes; they are single-byte inside the array. Like a field ... I needed to check; I assume that adding means that they can be considered as 4 bytes. A struct with sizeof should show ...

 struct Foo { byte a, b, c; } static class Program { unsafe static void Main() { int i = sizeof(Foo); // <==== i=3 } } 

Here i shows 3, so they are single-byte like fields, but (see codymanix comments) an additional addition may be needed when other types are involved - for example:

 struct Foo { byte a, b, c; int d; } 

is 8 bytes, due to the need for alignment d . Fun funny fun.

+7
source share

I think it depends on the target platform. On low memory devices, the CLR can decisively pack them, so it will save memory if you change the type of enumeration.

+2
source share

I do not think this is explicitly defined by the C # specification or even .NET. You should use the FieldOffset and FieldOffset attributes to specify the exact memory layout.

 [StructLayout(LayoutKind.Sequential, Pack=1)] struct TestDByte { public double a; public byte b; } 
+2
source share

Bytes do not need to be aligned in order to work efficiently on x86 processors (however, larger blocks). For other processor architectures, things may work differently.

+1
source share

All Articles