Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache the hash code when requested. #26

Closed
gafter opened this issue Mar 15, 2023 · 3 comments
Closed

Cache the hash code when requested. #26

gafter opened this issue Mar 15, 2023 · 3 comments

Comments

@gafter
Copy link
Member

gafter commented Mar 15, 2023

In many client scenarios, thee are types for which the generated code would be more efficient if it (1) computed the hash code at construction time and cached it, and (2) compares the hash codes when comparing for equality, to shortcut the potentially more expensive equality comparisons on the elements.

Specifically, code like this

Using AutoHashEquals

@auto_hash_equals_cached struct Q
    x::Int
end

would be translated to something like

struct Q
    x::Int
    _cached_hash::UInt
    Q(x) = new(x, hash(x))
end

@show_structure Base.hash(x::Q) = x._cached_hash
@show_structure Base.hash(x::Q, h::UInt) = hash(x._cached_hash, h)
@show_structure Base.:(==)(a::Q, b::Q) = a._cached_hash == b._cached_hash && isequal(a.x, b.x)
@show_structure Base.show(io::IO, x::Q) = print(io, "Q(", x.x, ")")

(I'm willing to do the work of implementing this.)

@gafter
Copy link
Member Author

gafter commented Mar 16, 2023

The function show shouldn't be defined if the user has already done so.

You cannot specialize a function on a type that hasn't been declared yet.

@gafter
Copy link
Member Author

gafter commented Mar 17, 2023

The implementation of show should correctly handle cyclic data structures in which Q in on the cycle.

@gafter
Copy link
Member Author

gafter commented Aug 18, 2023

The current latest version (not registered yet) supports all this.

@gafter gafter closed this as completed Aug 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant