Is there a difference in size between a String "a" and a Char 'a'? Should you use a Char when you need to save single letters or numbers?
Note there are actually 3 cases
String "a"
Character 'a'
char 'a'
of these, char 'a' will take up the least amount of space (2 bytes), whereas Char 'a' and String "a" are both objects and so because of the memory overhead associated with an Object, both will be approximately the same size
There is no size difference between a String
of one letter and a char
of one letter (referring to the backing char
array of the String
, that is). Currently, they both require 2 bytes as per UTF-16 encoding, but non UTF-16 characters will only require 1 byte once Java 9 is released in July.
The String
will obviously use up more memory than the primitive, but it sounds like you're prematurely optimizing.
Let's get something vaguely scientific going on here. I created the following program which creates an array of 100 million characters or strings:
public class NewClass {
private static final int SIZE = 100000000;
public static void main(String... args)
{
char[] a = new char[SIZE];
for (int i = 0; i < SIZE; ++i)
{
a[i] = 'a';
}
}
}
I profiled it once using char[]
, once using String[]
, and once using Character[]
.
The amount of used heap space:
char[] : 267 million bytes
String[] : 442 million bytes
Character[] : 437 million bytes
So char
is roughly 60% of the size of a 1 character String
, which is comparable in size to a Character
(on my JVM).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.