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

Question: Would it make sense to make val a Ref{T}? #46

Closed
EricForgy opened this issue May 4, 2020 · 1 comment
Closed

Question: Would it make sense to make val a Ref{T}? #46

EricForgy opened this issue May 4, 2020 · 1 comment

Comments

@EricForgy
Copy link

I'm looking at

mutable struct Observable{T} <: AbstractObservable{T}
    listeners::Vector{Any}
    val::T
    ...
end

and wondering if it would make sense to make that

struct Observable{T} <: AbstractObservable{T}
    listeners::Vector{Any}
    val::Ref{T}
    ...
end

so that Observable could be immutable and then

function Base.setindex!(observable::Observable, val)
    observable.val = val
    ...
end

becomes

function Base.setindex!(observable::Observable, val)
    observable.val[] = val
    ...
end

and

Base.getindex(observable::Observable) = observable.val

becomes

Base.getindex(observable::Observable) = observable.val[]

etc.

@twavv
Copy link
Member

twavv commented May 5, 2020

We discussed this on Slack so I'm going to post here for posterity.

Would it make sense to make val a Ref{T}?

Yes but it's probably not worth making this change.

The reasoning is essentially so that Observables could be immutable, which is appealing since immutable objects do not need to be heap-allocated. However, we'd simply be "punting" the heap allocation to the RefValue object (so while the Observable could be on the stack, the underlying value would still necessarily live on the heap). This seems(?) like it would only be beneficial for use cases where one is passing lots of Observables around but not actually attempting to read or set the data values associated with them.

On the other hand, it's possible the Refs would be more performant (I'm not sure what kind of existing performance optimizations exist around Refs, but they're essentially implemented as mutable struct RefValue; x::Any; end). Personally, I'd want to see measurable performance increases to commit to making that change (since all new code has the possibility to introduce new bugs/regressions).

I'm going to close but feel free to re-open if I missed something. :^)

@twavv twavv closed this as completed May 5, 2020
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

2 participants