Search code examples
c#.netbyteintshort

When to Use a Data Type Other Than int?


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 bytes 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 bytes or shorts instead of int?


Solution

  • 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).