6
votes

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

I see this in java documentation.My question is how the byte data type will save the memory in large arrays?.I confused with this

Thanks in advance....

2
In fact, when you load a file into memory, it is common to use an array of bytes. It is the most optimal way of doing it.Paul Vargas

2 Answers

10
votes

What it is saying is really very simple.

Suppose I have 40 "numbers" to store. If I store them in the following:

    byte[] numbers = new byte[40];

it will take less space than if I store them in the following:

    int[] numbers = new int[40];

Why? Because in an array, 40 byte instances occupies 40 bytes of memory, but 40 int instances occupies 40 x 4 = 160 bytes of memory.


Caveats:

  1. Obviously, this only works if the numbers are small enough to be represented as byte ... without overflow; i.e. they must be in the range -128 to +127

  2. This does NOT apply to simple variables. In Java a byte variable and an int variable typically occupy 4 bytes each. (It is a low-level JVM thing which would take a lot of explaining ...)

  3. I'm glossing over the fact that heap memory may be allocated at a granularity that is coarser than 4 bytes. The allocation granularity is typically 8 bytes. However, for large arrays, the contribution of the allocation granularity is negligible. Likewise, I am glossing over the contribution of array headers for the above reason, AND because the contribution header is the same irrespective of the array's base type.

1
votes

For instance you have an array of 1000000 integers. If you use int[] it will take up 4Mb of memory. But if you know that all values are within the range of -128 to 127 you can use byte[] and it will take up 4 times less memory