Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the byte data type can be useful for saving memory in large arrays

Tags:

java

byte

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

like image 840
PSR Avatar asked May 18 '13 06:05

PSR


1 Answers

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.

like image 111
Stephen C Avatar answered Oct 30 '22 07:10

Stephen C