When declaring an enum, should you force the type to byte for under 256 entities?

后端 未结 7 1602
夕颜
夕颜 2020-12-13 08:51

If you have an enum in your application and you only have a few items, should you force the underlying type to be the smallest possible type?

    enum smalle         


        
相关标签:
7条回答
  • 2020-12-13 09:13

    What would be gained? You'd save a whopping 3 bytes of memory, at the cost of slightly slower execution and less intuitive or readable code. (Reading this, I have to wonder whether pyou actually had a reason for making it a byte, and what that reason might have been. Presumably you went out of your way to use a non-default type for a reason).

    If you plan to store millions of these things then yes, saving a few bytes on each may pay off. Otherwise, no.

    It's the same reason you don't typically use byte or short instead of int.

    0 讨论(0)
  • 2020-12-13 09:18

    No. Don't prematurely optimize unless you've proved with a profiler that it's actually a problem.

    0 讨论(0)
  • 2020-12-13 09:21

    If you are mapping the model with enum to another model, or serializing it, or your enum is reflected to the database column – then I would suggest you to specify the type explicitly.


    Scenario: You have a column in database: status_id with type tinyint. And you have enum in your code: enum Status { Well = 1, Bad = 2 }. And you use this enum in some entity. Let's say you use entity frameworks core 2.0. If you try to read/write this entity from database you will get the error "Unable to cast object", unless you specify the byte type explicitly.

    0 讨论(0)
  • 2020-12-13 09:22

    In .Net core, if you call Enum.IsDefined to check if the passing in value existed in an enum, you should ensure types are the same.

    ArgumentException: Enum underlying type and the object must be same type or object must be a String.

    0 讨论(0)
  • 2020-12-13 09:23

    You should not assign a certain integer type to enumerations and let C# fall back to the default int1 but let the .NET environment figure out the best "size" for the enum. As JaredPar said, if you change the data type, you should definitely check whether it actually helps.

    The thing is that 32-bit integers are "natural" on x86 processors because they can be easily align in an optimal fashion.

    1 By default, the associated constant values of enum members are of type int

    0 讨论(0)
  • 2020-12-13 09:30

    The only reason to do this is if you are storing or transmitting this value using a defined protocol that demands the field to be of that size.

    0 讨论(0)
提交回复
热议问题