I need to create a space efficient 2D array for a large number of 8 bit values. I began writing my class using a few layers of abstraction and generics to allow for code reuse. Once I got to implementing the concrete class it occurred to me I cannot pass in a primitive type as a generic class argument and I would have to use a wrapper class. Because I am concerned about space efficiency, I need to know: what is the space efficiency difference between a Byte
array using the wrapper class compared to a primitive byte
array?
Yes, primitives are light-weight compared to corresponding Wrapper class objects.
You can read about it here : Primitives vs Wrappers
Accroding to http://www.javamex.com/tutorials/memory/object_memory_usage.shtml
byte[] size ~= 12 + length
Byte[] size ~= 12 + 20 * length (20 = 16 + 4 the size of 1 Byte object + 4 bytes reference)
so, Byte[] may take 20 times more memory than byte[]. It is actually maximum, it depends on the way you create a Byte. new Byte is always a new Object, Byte.valueOf is always a cached instance. It also depends on CPU, for x64 each reference takes 8 bytes.
Byte
objects are cached, or just integers, but even if they're not I would think that for any size Byte
array one could use a static Byte[256]
to hold an instance of each value; the overhead for that would be fixed at ~4096 bytes, each Byte[]
array that used cached instances would typically take 4 bytes per entry. –
Niobe Watch this other question: Wrappers of primitive types in arraylist vs arrays
The big issue with double versus Double is that the latter adds some amount of memory overhead -- 8 bytes per object on a Sun 32-bit JVM, possibly more or less on others. Then you need another 4 bytes (8 on a 64-bit JVM) to refer to the object.
So, assuming that you have 1,000,000 objects, the differences are as follows:
double[1000000]
8 bytes per entry; total = 8,000,000 bytes
Double[1000000]
16 bytes per object instance + 4 bytes per reference; total = 20,000,000 bytes
Whether or not this matters depends very much on your application. Unless you find yourself running out of memory, assume that it doesn't matter.
© 2022 - 2024 — McMap. All rights reserved.
objects
orints
in the same unique way I am currently storing 8 bit values, The 2D array is the concrete storage implementation but the class's data structure access control is unique. – Sunshade