views:

548

answers:

6

Is there a way to allocate an uninitialized block of memory, such as an array that contains whatever garbage happened to be left behind, in Java? I want to do so to benchmark how fast Java's memory allocator/garbage collector can allocate/free blocks of memory.

+6  A: 

No. You can't separate allocation from initialization, at least not for arrays.

What, exactly, are you trying to benchmark?

The reason that I ask is that there are a lot of variables within a running JVM that will affect any object allocation timing, ranging from the size of the object (which determines where it's allocated), to what else is happening in the JVM at the same time (once you start allocating objects, they'll get shuffled between the various generations), to whether or not Hotspot decides that your code isn't doing anything and can be replaced by a no-op.

Incidentally, there are a similar but non-overlapping set of variables that get in the way of benchmarking malloc() ...

kdgregory
doesn't 'new Object[200]' allocate space, but leave each entry un-initialized?
Cogsy
no, it initializes each entry to nullsee: http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc.html#anewarray
kdgregory
Or more accurate to the implementations, I believe the memory is already zeroed.
Tom Hawtin - tackline
+1  A: 

If you could do this you would be benchmarking something which doesn't happen in real programs so the result wouldn't mean anything.

I have done something similar to this and found that allocation takes about 250 ns 50% of the time and 500 ns or more 10% of the time and about 1,200 ns, 1 % of the time.

This depends on your processor speed, the memory architecture of your machine and what object you are creating.

Peter Lawrey
+1  A: 

I imagine that one of the reasons you can't do this is because of the security model.

Fortyrunner
You don't have to use Java with security. The philosophy of Java is to make things predictable (as much as reasonably possible), and zeroing everything is part of that.
Tom Hawtin - tackline
A: 

About the only way you could do what you are asking about is via JNI, which would make moot any benchmark you get as it would not reflect true Java usage. For the reasons others have already given. Any allocation via Java (via "new") will always initialize memory.

Eddie
+1  A: 

Maybe java.nio.ByteBuffer is what you are looking for. Your reasons are a bit vague though :-)

St3fan
A: 

There's no way to allocate an uninitialised block of memory and go through the "normal" allocation/GC mechanism.

What you can do is construct a direct ByteBuffer at an arbitrary memory address (from a native method). But that's not going to give you a benchmark of "normal" object handling (though if the thing you want to benchmark is normal allocation/deallocation, it's not clear why you want this).

Neil Coffey