Freak613 / 1more

MIT License
49 stars 1 forks source link

does 1more compile each template each time? #8

Closed gdeb closed 3 years ago

gdeb commented 3 years ago

I am confused by the getTemplate method (see https://github.com/Freak613/1more/blob/main/src/index.js#L898). It looks like it uses a cache to store compiled templates.

However, as far as I can tell, each call to the html method will return a different strings array in the first argument. So, that means that the cache will never work and each component update will actually trigger a complete recompilation of the html template. Is that correct, or is there something that I completely misunderstood?

Freak613 commented 3 years ago

Thing is that the first argument (array of static parts) is frozen and cached by browser between evaluations, thus allowing to implement cache. This feature is implemented by all major browsers and can be found in ecma spec of this feature, in Note 2:

Each TemplateLiteral in the program code of a realm is associated with a unique template object that is used in the evaluation of tagged Templates (12.2.9.6). The template objects are frozen and the same template object is used each time a specific tagged Template is evaluated. Whether template objects are created lazily upon first evaluation of the TemplateLiteral or eagerly prior to first evaluation is an implementation choice that is not observable to ECMAScript code.

As an example it can be tested by code like this:

const html = (...args) => args; // just return arguments array

const App = () => {
  return html`1`;
}

const a1 = App(); // [["1"]]
const a2 = App(); // [["1"]]
console.log(a1[0] === a2[0]); // logs true

So the answer is no, 1more does not recompile templates each time by using this technique to cache previous work.

gdeb commented 3 years ago

thank you!