java - 什么是缓存字符串?

标签 java c string java-native-interface

什么是缓存字符串?或者什么是字符串缓存?我在 JNI 中多次阅读过这个术语,但不知道它是什么。

最佳答案

A cache提高性能(这对 JNI 很重要)并减少内存使用量。

这是一个简单的字符串缓存示例,如果您对简单的缓存算法如何工作感兴趣 - 但这实际上只是一个示例,我不建议您实际在代码中使用它:

public class StingCache {

    static final String[] STRING_CACHE = new String[1024];

    static String getCachedString(String s) {
        int index = s.hashCode() & (STRING_CACHE.length - 1);
        String cached = STRING_CACHE[index];
        if (s.equals(cached)) {
            return cached;
        } else {
            STRING_CACHE[index] = s;
            return s;
        }
    }

    public static void main(String... args) {

        String a = "x" + new Integer(1);
        System.out.println("a is: String@" + System.identityHashCode(a));

        String b = "x" + new Integer(1);
        System.out.println("b is: String@" + System.identityHashCode(b));

        String c = getCachedString(a);
        System.out.println("c is: String@" + System.identityHashCode(c));

        String d = getCachedString(b);
        System.out.println("d is: String@" + System.identityHashCode(d));

    }

}

关于java - 什么是缓存字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10510857/

相关文章:

c++ - 将 16 位短数组转换为 32 位 int 数组的有效方法?

java - 在逗号、句号和其他标点符号后插入空格

c - 在 Xcode 中包含外部 C 库

c - scanf 总是打印输入的数字

java - 调用存储过程的批处理应用程序的正确 block 大小是多少?

java - Wicket 模型对象实例正在更改

python - 在Python中转义正则表达式unicode字符串

php - 如何用不会更新的新字母替换字符串中的字母

java - 在 Java 中检索正确的文件 URI

java - 如何完美模拟 KeyEvents?