By Default Java stores strings in UTF-16, in my application it is using huge memory. One of the suggestion we get is to convert UTF-16 to UTF-8 so some memory can be saved. is this True ?
If yes Can I convert it like this when I'm fetching it from DB?
new String(rs.getBytes("MY_COLUMNNAME"), StandardCharsets.UTF_8);
I tried a sample program to check the memory by googling by I don't see any difference in the size, am I going in correct way any leads are appreciated. below is the code snippet I tried
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
public class TestClass {
String value1;
String value2;
String value3;
String value4;
public TestClass(String x, String y, String z, String p) {
this.value1 = x;
this.value2= y;
this.value3 = z;
this.value4 = p;
}
public static long estimateObjectSize(Object obj) {
long size = 0;
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
Class<?> type = field.getType();
if (type.isPrimitive()) {
size += primitiveSize(type);
} else {
size += referenceSize();
}
}
size += objectHeaderSize();
return size;
}
private static long primitiveSize(Class<?> type) {
if (type == boolean.class || type == byte.class) {
return 1;
} else if (type == char.class || type == short.class) {
return 2;
} else if (type == int.class || type == float.class) {
return 4;
} else if (type == long.class || type == double.class) {
return 8;
} else {
throw new IllegalArgumentException("Unsupported primitive type: " + type);
}
}
private static long referenceSize() {
return 8;
}
private static long objectHeaderSize() {
return 16;
}
public static void main(String[] args) {
TestClass obj = new TestClass(new String("ABC".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8), new String("XYZ".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8),new String("XYZ".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8), new String("XYZ".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
TestClass obj = new TestClass("A", "B","C","D");
long size = estimateObjectSize(obj);
System.out.println("Estimated size of the object: " + size + " bytes");
}
}
staticfields to the object size and assume uncommon implementation details. The most common configuration is 64 bit with compressed oop & class pointers, where the object header is 12 bytes and the reference size 4 bytes. If you ever try your method on other classes thanString, you should also care for the fields of the superclasses. And, there’s no need forsetAccessible(true)here.