preactjs / signals

Manage state with style in every framework
https://preactjs.com/blog/introducing-signals/
MIT License
3.63k stars 88 forks source link

Question: Garbage Collection #483

Closed HappyStriker closed 6 months ago

HappyStriker commented 6 months ago

Hello,

I have a quick question about the garbage collection of signals, more specifically of the computed type. Lets look at the following code, which should use the signal time directly instead of time.value in the render method, but it is just a simplification for the demonstration:

import { Component, html, signal, computed, render } from './preact.js';

class App extends Component {
  static {
    this.clock = signal(new Date());
    setInterval(() => this.clock.value = new Date(), 1_000);
  }

  render() {
    const time = computed(() => App.clock.value.toTimeString('de').slice(0, 8));
    return html`
      <h1>Hello World, it is ${time.value} o'clock.</h1>
    `;
  }
}

render(html`<${App}/>`, document.body);

The class method render gets called every second in order to do get the latest vdom of the component. But what happens to the previous time signals? Do they automatically get garbage collected or is it my job as developer to clean up those signals to prevent any memory leaks?

Thanks for the clarification!

rschristian commented 6 months ago

They should get GC'd just fine.

That being said, you'd avoid any extra GC work by using useComputed in the render function. As it is, time has to be recreated on every rerender.

HappyStriker commented 6 months ago

They should get GC'd just fine.

That being said, you'd avoid any extra GC work by using useComputed in the render function. As it is, time has to be recreated on every rerender.

Thank you very much for the explanation.