Skip to content

Commit

Permalink
Add docstring for the flyweight factory function
Browse files Browse the repository at this point in the history
  • Loading branch information
bowenszhu committed Nov 5, 2024
1 parent cf937b0 commit 765293a
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,27 @@ end
### Constructors
###

"""
$(TYPEDSIGNATURES)
Implements hash consing (flyweight design pattern) for `BasicSymbolic` objects.
This function checks if an equivalent `BasicSymbolic` object already exists. It uses a
custom hash function (`hash2`) incorporating metadata and symtypes to search for existing
objects in a `WeakValueDict` (`wvd`). Due to the possibility of hash collisions (where
different objects produce the same hash), a custom equality check (`isequal2`) which
includes metadata comparison, is used to confirm the equivalence of objects with matching
hashes. If an equivalent object is found, the existing object is returned; otherwise, the
input `s` is returned. This reduces memory usage, improves compilation time for runtime
code generation, and supports built-in common subexpression elimination, particularly when
working with symbolic objects with metadata.
Using a `WeakValueDict` ensures that only weak references to `BasicSymbolic` objects are
stored, allowing objects that are no longer strongly referenced to be garbage collected.
Custom functions `hash2` and `isequal2` are used instead of `Base.hash` and `Base.isequal`
to accommodate metadata without disrupting existing tests reliant on the original behavior
of those functions.
"""
function BasicSymbolic(s::BasicSymbolic)::BasicSymbolic
h = hash2(s)
t = get!(wvd, h, s)
Expand Down

0 comments on commit 765293a

Please sign in to comment.