Java Character vs char: what about memory usage?
java, memory, performance
Solution
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.
Problem
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 `Character`s 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?