gd1
gd1

Reputation: 11403

Java Character vs char: what about memory usage?

In one of my classes I have a field of type Character. I preferred it over char because sometimes the field has "no value" and null seams to me the cleanest way to represent this (lack of) information.

However I'm wondering about the memory footprint of this approach. I'm dealing with hundred of thousands of objects and the negligible difference between the two options may now deserve some investigation.

My first bet is that a char takes two bytes whereas a Character is an object, and so it takes much more in order to support its life cycle. But I know boxed primitives like Integer, Character and so on are not ordinary classes (think about boxing and unboxing), so I wonder if the JVM can make some kind of optimization under the hood.

Furthermore, are Characters garbage collected like the other stuff or have a different life cycle? Are they pooled from a shared repository? Is this standard or JVM implementation-dependent?

I wasn't able to find any clear information on the Internet about this issue. Can you point me to some information?

Upvotes: 9

Views: 2119

Answers (3)

ZhongYu
ZhongYu

Reputation: 19672

Use int instead. Use -1 to represent "no char".

Lots of precedence of this pattern, for example int read() in java.io.Reader

Upvotes: 1

Fabien
Fabien

Reputation: 13406

As you stated, a Character object can be null, so it has to take more place in RAM than a regular char which cannot be null : in a way, Characters are a superset of chars.

However, in a given part of your code, the JIT compiler might be able to detect that you Character is never null an is always used as a regular char and optimize that part so that your Character uses no more RAM or execution is no slower. I'm just speculating on this very point, though, I don't know if a JIT can actually perform this precise optimization.

Upvotes: 0

AmitG
AmitG

Reputation: 10543

If you are you using Character to create character then prefer to use

Character.valueOf('c'); // it returns cached value for 'c' 

Character c = new Character('c');// prefer to avoid

Following is an excerpt from javadoc.

If a new Character instance is not required, this method Character.valueOf() should generally be used in preference to the constructor Character(char), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

Upvotes: 1

Related Questions