简体   繁体   中英

Java Byte/byte array space efficiency comparison

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM