What is a cached string?

What is a cached string? or What is string caching? I read this term several times in JNI, but I don’t know what it is.

+4
source share
1 answer

A cache improves performance (which is important for JNI) and reduces memory usage.

Here is a simple String cache example if you are interested in how a simple caching algorithm works, but it is really just an example, and I do not suggest you 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)); } } 
+1
source

Source: https://habr.com/ru/post/1411445/


All Articles