Re: How to get the current allocated total size of an ArrayList?
On 02/24/2011 07:14 AM, Roedy Green wrote:
On Wed, 23 Feb 2011 07:50:10 -0800, markspace<-@.> wrote, quoted or
indirectly quoted someone who said :
How can I find out the total size (in Bytes) which is currently allocated by the ArrayList?
Occasionally I get an OutOfMemory exception. Can I prevent this by preallocating everything in one step
in advance instead of doing this little by little with every add()?
It it the space needed for each string + some the overhead of the
array
Count on roughly 16 bytes overhead per object, 2 bytes per char, and 4
bytes for the length of each string.
Count on 4 bytes or 8 bytes per reference (if using 32/64 bit JVM) in
You cannot count on 8 bytes per reference in 64-bit JVMs. They also support
4-byte references.
the array pointing to the Strings. There is some other junk, but that
is the bulk of it.
You can't preallocate space for the strings, other than my creating
the literal strings. Even then, you do it one string at a time.
And of course, with literal strings you put them into the intern pool, not
regular heap.
You can improve efficiency by guessing the correct size when you
allocate the ArrayList.
Nice myth.
It's a myth because it's next to impossible to guess right except in very,
very restricted cases, pretty much for which general algorithms aren't
suitable. If you are able to guess right about the size, you'd want an array
rather than an 'ArrayList' (or any other 'List').
Hotspot messes up your calculations under certain circumstances, too.
This is clearly a case where the OP should do the right thing instead of what
he's asking.
--
Lew
Honi soit qui mal y pense.