next up previous contents
Next: 5.10.3 Arrays Up: 5.10 Object Representation Previous: 5.10.1 Think Before You

5.10.2 Structure Representation

  One of the best ways of building complex data structures is to define appropriate structure types using  defstruct. In Python, access of structure slots is always at least as fast as list or vector access, and is usually faster. In comparison to a list representation of a tuple, structures also have a space advantage.

Even if structures weren't more efficient than other representations, structure use would still be attractive because programs that use structures in appropriate ways are much more maintainable and robust than programs written using only lists. For example:

(rplaca (caddr (cadddr x)) (caddr y))
could have been written using structures in this way:
(setf (beverage-flavor (astronaut-beverage x)) (beverage-flavor y))
The second version is more maintainable because it is easier to understand what it is doing. It is more robust because structures accesses are type checked. An astronaut will never be confused with a beverage, and the result of beverage-flavor is always a flavor. See sections 5.2.8 and 5.2.9 for more information about structure types. See section 5.3 for a number of examples that make clear the advantages of structure typing.

Note that the structure definition should be compiled before any uses of its accessors or type predicate so that these function calls can be efficiently open-coded.



Raymond Toy
Mon Jul 14 09:11:27 EDT 1997