Java object size overhead...

I did some tests creating lots of objects, I calculated that an empty Java object carries around 22 bytes of overhead. My test was to instantiate 20 million objects (class that has only a default constructor) on the heap and then watch windows process size.
I know this is not a rocket science kind of benchmark but it really bothers me that when I Instantiate lets say a million Point3fs two thirds of the memory consumed goes somewhere. Now, can somebody shed some light and provide more details on why is this normal and can this be worked around.

It can be more than 22bytes; depends on VM implementation.

I’m sure there must be some public documentation from Sun explaining the in-memory representation of an Object instance.

32-bit OS: 2x4=8 bytes overhead per object
64-bit OS: 2x8=16 bytes overhead per object

arrays take like 12 more bytes.

(Sun Hotspot VM)

Work around it by not creating a million objects. Use the flyweight pattern instead.

Cas :slight_smile:

[quote]32-bit OS: 2x4=8 bytes overhead per object
64-bit OS: 2x8=16 bytes overhead per object

arrays take like 12 more bytes.

(Sun Hotspot VM)
[/quote]
In this case 20 million objects would eat up around 160 Megs, references for these guys should be additional 80 Megs. Instantiating all these objects and storing into array end up using 436Megs according to windows task manager and using (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) on windows xp (32-bit). Am I wrong assuming that this should average in the range of 260-280 Megs.

Cheers

[quote]Work around it by not creating a million objects. Use the flyweight pattern instead.
[/quote]
How would this pattern work for 20 million unique points?

Sorta like this:


class LotsaPoints {

	private float[] x, y;

	LotsaPoints(int size) {
		x = new float[size];
		y = new float[size];
	}

	Point getPoint(int index) {
		return new ImmutablePoint(x[index], y[index]);
	}

	void setPoint(int index, ImmutablePoint p) {
		x[index] = p.getX();
		y[index] = p.getY();
	}
}

Cas :slight_smile:

Kinda; Not at all, too bad… ;D

Thanks