Svelte: Immutable option/configuration for Stores

Created on 3 Feb 2018  Â·  2Comments  Â·  Source: sveltejs/svelte

It would be great if Store (and Store/Svelte's computed properties) could have a configuration option to make it un-conservative when it is known the data will be immutable. That is, make it assume objects never mutate and make the comparisons always treat values as immutable.

I have a data store that is immutable (like Redux) and this could help with performance, particularly with computed properties that perform calculations with objects and arrays as inputs. Array sorts and other slower data computations could be calculated just once when their value changes instead of every time any value is changed.

In the docs there is a note that "Store is conservative about objects and arrays, because there is no easy way to know if they have been mutated." If you know in your application your store only holds immutable data, this could be a nice improvement.

Questions this raises:

  • Can you only check store values differently, or would you need to change all computed properties to assume immutable objects?
  • Should there be an configuration to treat all objects as immutable (not just store data)?

Most helpful comment

I've wondered about this. The relevant code is here — it could be as simple as adding a differsImmutable helper like this...

export function differs(a, b) {
  return a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}

export function differsImmutable(a, b) {
  return a !== b;
}

...and using the immutable version if a compiler option was set, the same way you can opt into [thing]Dev helpers with the dev: true option.

Store uses the same differs helper. Presumably we could do something like this...

const store = new Store({ some: 'data' }, { immutable: true });

...and it would use differsImmutable instead.

All 2 comments

I've wondered about this. The relevant code is here — it could be as simple as adding a differsImmutable helper like this...

export function differs(a, b) {
  return a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}

export function differsImmutable(a, b) {
  return a !== b;
}

...and using the immutable version if a compiler option was set, the same way you can opt into [thing]Dev helpers with the dev: true option.

Store uses the same differs helper. Presumably we could do something like this...

const store = new Store({ some: 'data' }, { immutable: true });

...and it would use differsImmutable instead.

This is released as 1.55 — thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mmjmanders picture mmjmanders  Â·  3Comments

noypiscripter picture noypiscripter  Â·  3Comments

angelozehr picture angelozehr  Â·  3Comments

ricardobeat picture ricardobeat  Â·  3Comments

AntoninBeaufort picture AntoninBeaufort  Â·  3Comments