When developers use `async` functions, they'll likely also await
unconditionally any callback, even if such callback could return a non
promise value, for whatever reason.

Engines are great at optimizing stuff, but as of today, if we measure the
performance difference between this code:

```js
(async () => {
  console.time('await');
  const result = await (async () => [await 1, await 2, await 3])();
  console.timeEnd('await');
  return result;
})();
```

and the following one:

```js
(/* sync */ () => {
  console.time('sync');
  const result = (() => [1, 2, 3])();
  console.timeEnd('sync');
  return result;
})();
```

we'll notice the latter is about 10 to 100 times faster than the
asynchronous one.

Sure thing, engines might infer returned values in some hot code and skip
the microtask dance once it's sure some callback might return values that
are not promises, but what if developers could give hints about this
possibility?

In a twitter exchange, one dev mentioned the following:

> I often write:
> let value = mightBePromise()
> if (value && value.then)
>   value = await value
> in hot code in my async functions, for precisely this reason (I too have
measured the large perf difference).

so ... how about accepting a question mark after `await` so that it's clear
the developer knows the function might return non Promise based results,
hence the code could be faster?

```js
const value = await? callback();
```

Above code is basically what's this thread/proposal about, adding a
conditional `await` syntax, so that if the returned value is not thenable,
there's no reason to waste a microtask on it.

What are your thoughts?
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to