Hi,
I was wondering how much a difference does packing data to take smaller amount of memory make in Java.
In C++, let’s say I have a struct like this:
struct MyTile
{
int x,y;
bool bTaken;
};
This struct will take 4+4+2 = 10 bytes. If I have an 1000x1000 map then it will take 10.000.000 bytes = 9.5 MB.
So now I take that neither x or y can contain a number larger than 1000 due to the map size. The number 1000 can be contained in 10 bits, so for both numbers I only need 20 bits. The boolean bTaken can only be of value 1 and 0, so that’s one bit. All in all I can place the entire struct in 21 bits, and because one int is 32 bits I can place the entire struct in one int. This way I’ll be using only 4x1000x1000 = 4.000.000 bytes = 3.8 MB, so I saved about 5 MB of memory with that compression.
Can this same thing be done in Java? I mean I know there are bit operators, but how much actual memory will I save by doing this. Instead of a struct I would probably have a class. How much memory does a class take?
I’m guessing it’s probably more efficient to create 1 million ints that to create 1 million classes which hold 1 int, am I right?