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 b2afdf6
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,25 @@ end
### Constructors
###

"""
$(TYPEDSIGNATURES)
Implements hash consing (flyweight design pattern) for `BasicSymbolic` objects.
This function checks if an equivalent `BasicSymbolic` object already exists based on a
custom hash (`hash2`) and equality check (`isequal2`) that incorporate metadata and
symtypes. If an equivalent object is found in the `wvd` (a `WeakValueDict`), the existing
object is returned. Otherwise, the input `s` is returned. This approach reduces memory
usage, improves compilation time for runtime code generation, and supports built-in common
subexpression elimination, especially beneficial when dealing with duplicate symbolic
expressions.
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.
The custom `hash2` and `isequal2` functions are used instead of `Base.hash` and
`Base.isequal` respectively to avoid breaking existing tests that rely on the default
behavior of these functions, which does not consider metadata.
"""
function BasicSymbolic(s::BasicSymbolic)::BasicSymbolic
h = hash2(s)
t = get!(wvd, h, s)
Expand Down

0 comments on commit b2afdf6

Please sign in to comment.