加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 什么是缓存字符串?

发布时间:2020-12-15 02:34:08 所属栏目:Java 来源:网络整理
导读:什么是缓存的字符串?或什么是字符串的缓存?我在JNI已经多次读过这个术语,但不知道它是什么. 解决方法 cache提高了性能(这对JNI很重要)并减少了内存使用量. 这是一个简单的String缓存示例,如果您对简单的缓存算法如何工作感兴趣 – 但这只是一个示例,我不建
什么是缓存的字符串?或什么是字符串的缓存?我在JNI已经多次读过这个术语,但不知道它是什么.

解决方法

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

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

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));

    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读