Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of empty Java String

I heard a colleague say that I would pay "24 bytes" if I dropped a String member in a Java class, even if the String is empty. Is that accurate? Is it the same for Integer, Float, Double? (as opposed to int, float, double, which would be only 4, 4 and 8 bytes each).

like image 930
Frank Avatar asked Aug 17 '12 15:08

Frank


1 Answers

You'll pay 4 or 8 bytes for the reference. Whether you'll pay for an extra object per instance of your "container" object depends on how you get your empty string. For example, if you use the literal "" then all the instances will refer to the same object, so you'll only need to pay for the reference itself.

If you're creating a separate empty string for each instance, then obviously that will take more memory.

like image 152
Jon Skeet Avatar answered Oct 19 '22 06:10

Jon Skeet