Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does creating a big Java array consume so much memory?

Why does the following line

    Object[] objects = new Object[10000000];

result in a lot of memory (~40M) being used by the JVM? Is there any way to know the internal workings of the VM when allocating arrays?

like image 902
Manuel Selva Avatar asked Nov 27 '22 20:11

Manuel Selva


2 Answers

Well, that allocates enough space for 10000000 references, as well as a small amount of overhead for the array object itself.

The actual size will depend on the VM - but it's surely not surprising that it's taking up a fair amount of memory... I'd expect at least 40MB, and probably 80MB on a 64-bit VM, unless it's using compressed oops for arrays.

Of course, if you populate the array with that many distinct objects, that will take much, much more memory... but the array itself still needs space just for the references.

like image 86
Jon Skeet Avatar answered Dec 01 '22 01:12

Jon Skeet


What do you mean by "a lot of memory"? You allocating 10000000 pointers, each taking 4 bytes(on 32 bit machine) - this is about 40mb of memory.

like image 38
Alex Reitbort Avatar answered Dec 01 '22 01:12

Alex Reitbort