I'm reading a book about C# (Pro C# and the .NET 4 Platform by Andrew Troelsen) and I've just read this paragraph:
Changing the underlying type of an enumeration can be helpful if you are building a .NET application that will be deployed to a low-memory device (such as a .NET-enabled cell phone or PDA) and need to conserve memory wherever possible.
Is it true that bytes use less memory? Aren't they stored on 4 bytes for performance reasons? I remember reading the latter somewhere but I can't find any info about it, not even in the C# specification.
It isn't simple. As variables in a method, they are pretty much the same as int
, so 4-byte; inside an array they are single-byte. As a field... I'd need to check; I guess padding means they may be treated as 4-byte. A struct
with sizeof
should reveal...
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 as fields, but (see comments by codymanix) additional padding may be needed when other types get involved - for example:
struct Foo
{
byte a, b, c;
int d;
}
is 8 bytes, due to the need of d
to be aligned. Fun fun fun.
I think it depends on the target platform. On "low-memory"-devices, the CLR may choose to pack them tightly, so it will save memory if you change the enumeration type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With