Java 内存 UTF-16 与 UTF-8

问题描述 投票:0回答:1

默认情况下,Java 以 UTF-16 存储字符串,在我的应用程序中它使用大量内存。我们得到的建议之一是将 UTF-16 转换为 UTF-8,这样可以节省一些内存。这是真的吗?

如果是的话,当我从数据库中获取它时,我可以这样转换它吗?

new String(rs.getBytes("MY_COLUMNNAME"), StandardCharsets.UTF_8);

我尝试了一个示例程序,通过谷歌搜索来检查内存,我没有看到大小有任何差异,我是否以正确的方式进行,任何线索都会受到赞赏。下面是我尝试过的代码片段

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");
    }
}
java memory memory-management java-memory-model memory-optimization
1个回答
0
投票
new String(rs.getBytes("MY_COLUMNNAME"), StandardCharsets.UTF_8);

这对于字符串在内存中的存储方式绝对没有影响。

如果您想以 UTF-8 存储某些内容,则根本不能使用

String
,而必须使用
byte[]
或其他字节数组包装器。

© www.soinside.com 2019 - 2024. All rights reserved.