Friday, March 14, 2008

It gets worse

Yesterday, I described my surprise at learning the true sizes of various Java Objects. What I didn't mention is that the sizes I was looking at were for a 32-bit JVM. Later yesterday, I tested out the same code on a 64-bit JVM. Egad. It gets worse. Sizes for various Java Objects:
32-bit64-bit
Object816
Integer1624
Long1624
Float1624
Double1624
String4064
Date2432
Calendar432544
byte[0]1624
byte[32]4856
byte[128][0]25764120
ArrayList<Integer>(1)5696
ArrayList<Integer>(2)80128

Thursday, March 13, 2008

The size of a java.util.Calendar is 432 bytes

Calendar's are cool. They're one of the few objects (in any language) which I consider to have solved the datetime problem. So many datetime objects require extra work from the programmer for (seemlingly) simple queries such determining whether x occurred before or after a month ago. You typically can't simply add a year/month/date/hour/etc. and you always have to be careful of whether an index value is 0, 1, or -1900 based. Calendar lets you focus on the date operations you are performing rather than devising tricks to get around other people's laziness. You can add just about any date/time quantity, there are static fields for month values, and you can compare two Calendar's via the before and after methods.

But, recently, my love of Calendar's took a big hit. This was shortly after I stumbled upon Java Tip 130: Do you know your data size? I was tempted to discount this article due to it's age---5.5 years---so much has changed since then in the Java world. But, after running the SizeOf code and discovering that memory consumption for the various basic objects Vladimir Roubtsov tested hadn't changed, I re-read his article carefully and took every word to heart. That an empty String consumes 40 bytes took me by surprise. But, it wasn't until I tested Calendar that I was truly shocked. In the current system I'm working on, I am storing hundreds-of-thousands of objects with Calendar's as fields. No wonder they consumed so much memory! Now I understand whence that outlandish consumption came.

Going forward, I won't stop using Calendar's, but I'll be much more careful about my usage of them. No more throwing a Calendar into an object that I'll allocate thousands of times...

Other useful articles on memory usage: