Most efficient data type for entering fixed numbers

I have JSON that fits my Java program. It has a specific field with six fixed numbers: 0, 30, 60, 120, 240, or 480. Is it possible in Java to choose a better data type than short? Maybe by enumerating in some form, or by representing the input in bits, pre-using a pre-fixed input?

As far as enums go, they seem to be made for a different use case, from the Oracle Java docs for enumeration, it looks like if I use an enum it will still create an int internally, so I don't see any benefit ultimately in speed or memory. Is there something I can't see?

I tried google but couldn't get a proper answer.

+3


source to share


1 answer


First, notice that the numbers in your example follow a certain pattern - they are built from two values ​​multiplied by 30:

  • 0 - 0 - 0*30

  • 1 - 2 0 -1*30

  • 2 - 2 1 -2*30

  • 4 - 2 2 -4*30

  • 8 - 2 3 -8*30

  • 16 - 2 4 -16*30

If you are storing a small number between 0 and 5, inclusive, you can compute the target number back either with a lookup table or with a simple bit offset expression:



byte b = ... // Store the value in a variable of type "byte"
int num = b!=0 ? 30*(1<<(b-1)): 0;

      

Note: Because it enum

is a full-sized class, it usually uses the same or more space as a primitive number.

+3


source







All Articles