4

キャッシュされた Stringとは何ですか? または文字列のキャッシュとは何ですか? 私はこの用語を JNI で何度か読んだことがありますが、それが何であるかはわかりません。

4

1 に答える 1

1

キャッシュはパフォーマンス (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));

    }

}
于 2012-05-09T06:48:08.833 に答える