Hash consing
In computer science, particularly in functional programming, hash consing is a technique used to share values that are structurally equal. When a value is constructed, such as a cons cell, the technique checks if such a value has been constructed before, and if so reuses the previous value, avoiding a new memory allocation. A useful property of hash consing is that two structures can be tested for equality in constant time via pointer equality, which in turn can improve efficiency of divide and conquer algorithms when data sets contain overlapping blocks. Hash consing has been shown to give dramatic performance improvements—both space and time—for symbolic and dynamic programming algorithms.
Hash consing is most commonly implemented with hash tables storing weak references that may be garbage-collected when the data stored therein contains no references from outside the table.
Example
The following is a simple demonstration of a memoizer by means of hash table and weak references in Scheme. Thebwp-object function returns true if the reference given is a broken weak pointer, i.e., the target has been garbage-collected.;; weak hashes
;;
)
))))
))
;; memoizer factory: for given procedure,
;; return a procedure which does the same memoizing some of results
;; in the sense of equal? on the whole list of args
;;
r)
x)))))