If I have an object, for example...
String city = "Chicago"
and I have millions of them. Let's say I take the byte of those million objects,
byte[] cityByte = "Chicago".getBytes()
Would byte take less space in memory?
edit: more in-depth:
I have several com.microsoft.azure.servicebus.Message objects. I intend to use SerializationUtils from Apache Commons Lang to get the byte array of each object and store it in a List.
I was thinking that if I store 1 million Message objects in a List, that might cause an issue. But if I store the same million objects as a byte array in a List, I will have a little more memory left so I can do other stuff. Hence the question.
I used JOL1 to determine the actual size of the objects in memory at runtime:
import org.openjdk.jol.info.GraphLayout;
public class MainClass {
public static void main(String[] args) {
String city = "Chicago";
byte[] cityByte = "Chicago".getBytes();
System.out.println(GraphLayout.parseInstance(city).toPrintable());
System.out.println(GraphLayout.parseInstance(cityByte).toPrintable());
}
}
output:
java.lang.String@4d7e1886d object externals:
ADDRESS SIZE TYPE PATH VALUE
76ac826d8 24 java.lang.String (object)
76ac826f0 32 [C .value [C, h, i, c, a, g, o]
[B@3caeaf62d object externals:
ADDRESS SIZE TYPE PATH VALUE
76ac82738 24 [B [67, 104, 105, 99, 97, 103, 111]
Conclusion: 'String' 32 bytes VS 'byte[]' 24 bytes
P.S. Results may vary depends on JVM version and options. Try the same approach in your environment. Run at jdk_1.8.0_161 Mac OS 10.14