Skip to content

Leverage types for perf improvements #418

Closed
@Rich-Harris

Description

@Rich-Harris

Moving #415 (comment) into its own issue.

There are certain places where Svelte could use type information to generate more compact or efficient code.

The big win is probably in recompute (formerly applyComputations) where we can shortcut the conditional that determines whether a given computed value's dependencies may have changed. There are other cases as well, e.g. this...

<div class='{{foo}} {{bar}}'></div>

...results in this code...

var div = createElement( 'div' );
div.className = "" + ( root.foo ) + " " + ( root.bar );

...which could easily become this, if we had confidence that foo was a string:

var div = createElement( 'div' );
div.className = root.foo + " " + root.bar;

(The unnecessary parens are a separate matter — they're included defensively but unnecessarily in most cases. A minifier can see to those though, whereas it can't remove the leading "" +).

The easiest way to get the type information would be to analyse the template — if {{a.b}} is encountered we know a is non-primitive, if {{a()}} is encountered we know it's a function, and if {{#each a as x}} is encountered we know a is array-like. (Or rather, we know that the component would fail anyway if those assumptions proved incorrect, in which case we lose nothing by making the assumption.)

There are other bits of static analysis we could do but they are far less straightforward and probably prone to uncertainty, which we should avoid.

We could also allow users to specify type information:

<script>
  export default {
    data () {
      return {
        foo: couldBeAnything,
        bar: couldAlsoBeAnything,
        baz: whoKnows
      };
    },

    types: {
      foo: Object,
      bar: Array,
      baz: String
    }
  };
</script>

This would only be used for SA, and removed from the compiled output. In dev mode, we could add warnings if the wrong type is supplied.

Finally, it might be possible to use Flow to more sophisticated type inference. No idea how that would work in practice though.

Metadata

Metadata

Assignees

No one assigned

    Labels

    compilerChanges relating to the compilerperf

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions