Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 391
gd1 Avatar asked Mar 22 '13 09:03

gd1


People also ask

How much memory does a char use in Java?

A variable of type char occupies two bytes in memory. The value of a char variable is a single character such as A, *, x, or a space character. The value can also be a special character such a tab or a carriage return or one of the many Unicode characters that come from different languages.

What is the difference between char and character in Java?

char is a primitive type that represents a single 16 bit Unicode character while Character is a wrapper class that allows us to use char primitive concept in OOP-kind of way. Thanks for your answer.

How much memory does a character in a String take?

For a default encoding, it will take 1 byte for a character. So Answer is 1 byte for default encoding.

What is the point of char in Java?

Definition and Usage The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.


2 Answers

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.

like image 118
AmitG Avatar answered Sep 21 '22 05:09

AmitG


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

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

like image 21
ZhongYu Avatar answered Sep 21 '22 05:09

ZhongYu