vinum-team / Vinum

A modern reactive state management library for correctness and speed.
MIT License
16 stars 1 forks source link

Gradual Dependency Tree Caching #3

Closed sinlerdev closed 1 year ago

sinlerdev commented 1 year ago

Gradual Dependency Tree Caching (that I will call GDTC since it is a long term) is something that would definitely increase performance, depending on how you use calculator-based objects (Match, Calc).

Consider this example:

Calc(function(useState)
    return useState(one) or useState(two)
end, JustOk) 

Scenario 1

Imagine one is a truthy value, and we don't care about two's value for now as well. if one was changed three times, and the three times, the newValue was truthy, it would still trigger a dependencies recapture (detection + tree simplification).

This means that we are spending some time recapturing the same dependencies. While this is a basic example, it gets worse with more advanced usage.

Consider this:

Calc(function(useState) 
    local x = useState(x)
    local y = useState(y)
    local z = useState(z)
    local d = useState(d)

    return x + y + z + d
end, JustOk)

This is just a basic demonstration of calc usage which we don't care about lazy evaluation (and we don't need it either). This time, x, y, z, d state objects get recaptured every time the update- despite there are no differences in every case.

Scenario 2

repost:

Calc(function(useState)
    return useState(one) or useState(two)
end, JustOk) 

Imagine that is one is always a falsy value, so in every case, we are going to use two's value. An update occurred to one, but its obviously a falsy value, so even though dependencies aren't going to change, we're still recapturing the same dependencies.

Solution: GDTC

A solution to this issue is to implement gradual caching for dependencies trees. It is gradual, because at creation, it is very possible to not be able to predict all the dependencies we are going to use (we could manually pass our dependencies and make useState and useKeyState do some internal job to let us know what dependencies we are currently using), although it can have an instant effect and make calc/match updating blazingly fast after creation (since technically, these objects' creation use the same mechanism as u[dating them)

sinlerdev commented 1 year ago

deferred to V0.3