< Zurück | Inhalt | Weiter >

C.2 Primitives and the geometry cache

A feature of the Primitive−derived classes is that they support the geometry cache (or some of them do). The geometry cache is intended to save CPU time when building Primitive−derived objects by caching GeomBuffer objects and returning them as appropriate. For example, if your application requires 100 Spheres with radius 50, the geometry cache will create the geometry for the first sphere and return this geometry for the remaining 99. Mysteriously, only the Cone, Cylinder, and Sphere Primitives use the geometry cache.

The source code to implement the geometry cache is useful because it presents an object lesson in how not to design such a facility. The geometry cache is implemented using a static hashtable of String keys that are used to retrieve an Object instance (in this case, GeomBuffer). The Strings that are used as keys are built from four int and three float parameters. Problems with this crude, inefficient, and simplistic design are:

The design is not extensible. Three ints and three floats were arbitrarily chosen to uniquely designate a geometric Primitive. If a

Primitive−derived object cannot be uniquely described using these parameters, the architecture will fail. A better architecture would have been to store each Primitive type in its own Hashtable and use the relevant object’s hashCode function to generate an int key to reference the geometry. In this way, responsibility for generating hash codes is delegated to the derived class (as is customary in Java), and there can be no interaction between derived classes since they are stored in separate Hashtables.

Using Strings to look up the objects in the geometry cache wastes

memory as well as CPU time. String manipulations are relatively costly and are wholly unnecessary in this context.

The geometry cache can help with saving only a few CPU cycles

involved with creating the geometry—it does not save any runtime memory or help consolidate objects.

Since the static Hashtable is never emptied, memory consumption is

increased because cached Geometry objects are never dereferenced and garbage collected.


From Primitive.java
protected GeomBuffer getCachedGeometry( int kind, float a, float b,
From Cylinder.java