I have a project in which I have many objects with many properties whose values will always be less than small numbers like 60, 100, and 255.
I'm aware that when doing math on byte
s it is necessary to cast the result. But other than that, is there any disadvantage to using a byte
or a short
for all these properties? Or another way of looking at it, is there any advantage to using byte
s or short
s instead of int
?
byte
s and short
s are useful in interop scenarios, where you need a datatype that is the same size as the native code expects.
They can also save memory when dealing with very large sets of data.
In general, use the type that makes sense. This can be helpful from data validation, integrity and persistence standpoints.
Typically, for instance, a bool
will actually consume 4-bytes on a 32-bit architecture, perhaps 8-bytes on a 64-bit architecture due to padding and alignment issues. Most compilers will, by default, optimize for speed and not code size or memory usage. Aligned access is typically faster than unaligned access. In .Net, some of this can be controlled via attributes. To my knowledge, the JIT compiler makes no effort to compact multiple boolean types into an integer bit field.
The same would hold true for byte
types. The JIT compiler could compact multiple byte types (and even rearrange storage order) to share the same word (assuming you don't override such behavior with attributes such as StructLayout
and FieldOffset
).
For instance:
struct Foo
{
string A;
short B;
string C;
short D;
}
Treating reference types as pointers, the above would likely have a size of 16 (maybe 14, but aligned to 16).
Foo
could be rearranged such that the order would actually be:
struct Foo
{
string A;
string C;
short B;
short D;
}
The above would likely have a size of 12, and an alignment of 12 or 16 (probably 16).
...potentially, in this contrived example, you could save 4 bytes due to rearrangement. And do note that .Net is more aggressive about realigning members than a typical C++ compiler is.
(On an aside, I recently spent some effort in a C++ library I maintain. I was able to achieve a 55% reduction in memory usage purely by optimizing member layout).
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