Frage

I have two Java classes. The first one is called "Index", and the second one, temporarily, I called it "IndexCache":

public class IndexCache {
    private static Map<String, Index> map = null;

    static {
        map = new HashMap<String, Index>();
    }

    @Override
    public Index getIndexString(key) {
        Index index = map.get(key);

        if (index == null) {
            index = new Index("yadayadayada");
            map.put(key, index);
        }

        return index;

    }

}

As you can see, IndexCache keeps a map of the Index objects to avoid to create the same object once and again.

Well, what programming technique is this? What would be its name?

War es hilfreich?

Lösung

It's called a cache, the technique is called caching.

A cache is something that stores data in order to speed up further requests for that same data. That data may be the result of some expensive computation and thus be cached to avoid repeating that costly computation. It might also be a copy of some data that is already pre-computed elsewhere but is costly to retrieve (e.g. caching filesystem blocks from a slow harddisk in RAM or caching HTTP documents from a remote server on a local proxy cache).

A cache is populated dynamically with different values each time, and may also grow and shrink.

This is different from a lookup table, which is populated statically, always with the same values, often even hardcoded into the source code or pre-computed at compilation time.

Memoization is a special case, it refers specifically to caching the results of function application with the same arguments.

Lizenziert unter: CC-BY-SA mit Zuschreibung
scroll top