Java – what is a cached string?

What is a cached string? Or what is string caching? I've read this term many times at JNI, but I don't know what it is

Solution

Cache improves performance (which is important for JNI) and reduces memory usage

This is a simple example of string caching. If you are interested in how a simple caching algorithm works - but this is only an example, I don't recommend that you actually use it in your code:

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

    }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>