Idea: Reflect.hasExternalReference

Andrea Giammarchi andrea.giammarchi at gmail.com
Sun Jan 15 10:34:18 UTC 2017


I am not sure how feasible this concept is, and I'll start just with the
pattern it's useful for.

```js
someRef.setup({
  one: 'or more',
  runtime: 'definition'
});
```
In JS user-land, the amount of unnecessary duplicated objects is
embarrassing.

We all know that immutability is great and we all know that functions
should never mutate received arguments, but there is absolutely zero side
effect in modifying, changing, erasing, you name it, an object passed like
the one in that `.setup({...})`

As of today, basically every method used to setup one-off objects will use
one of the following techniques:

  * a shallow copy via `Object.create(Object.getPrototypeOf(options),
Object.getOwnPropertyDescriptors(options))`
  * an enumerable only copy via `Object.assign({}, options)`, probably more
common but yet, most of the time, practically unnecesary

Things become even more difficult to improve when it comes to simply
chaining objects together, where it's not possible to simply define the
prototype of the received object, throwing away a performance boost
possibility like the one Netfilx recently had [1]

Shortcutting and destructuring also makes the usage of one-off literals
great, and states are the most basic, yet common, example.

```js
component.setState({
  label,
  user,
  time: Date.now()
});
```

## Back to the Reflect.hasExternalReference idea

Within the hypothetical `.setState(...)` method, invoking
`Reflect.hasExternalReference` would return `true` it the object was passed
as literal, without any possible external reference.

```js
class Component {
  setState(state) {
    this.state = Reflect.hasExternalReference(state) ?
      Object.assign({}, this.state, state) :
      Object.setPrototypeOf(state, this.state);
    // update only differences
    this.render(Object.keys(state));
  }
}
```
If there was a way to know passed literals, I am sure a lot of software
could automatically boost performance:

  * less polluted GC
  * more recycled one-off objects
  * less need to copy/clone over and over one-off literals that couldn't be
mutate anywhere else anyway

What do you think? Does any of this make sense?

Best Regards




[1]
http://techblog.netflix.com/2017/01/crafting-high-performance-tv-user.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170115/5f6361ff/attachment.html>


More information about the es-discuss mailing list