glayzzle/php-runtime

SPEC: Async code execution

Opened this issue · 2 comments

Some readings before :

Purpose :

  • Be able to natively support asynchronous calls in a synchronous syntax
  • Be able to handle promises natively in a synchronous manneer

Should be able to write :

<?php
function async() : promise {
  return new Promise(function($done, $reject) {
    setTimeout(function() use($done) {
      $done(true);
    }, 1000);
  });
}
echo async() . "\n";
echo "**done**\n";

An in order to avoid generators/yield with their overhead, should be also be able to use the promise contract :

<?php
function async() : promise {
  return new Promise(function($done, $reject) {
    setTimeout(function() use($done) {
      $done(true);
    }, 1000);
  });
}
async()->then(function($result) {
  echo "$result\n";
  echo "**done**\n";
});

Bad news, benchmark results, on same algorithm :

Generators : 2900 ms
Async/Await : 2500 ms
Classic : 14ms

It's just about 180 times more slower than a classic function call.

Lets take this code :

function fibo() {
  // classic code without async calls
}
async function readFile() {
  // async read a file
}

And lets say I write a classic function :

async function main() {
  let result = fibo();
  let contents = await readFile();
}

So if a function/closure calls an async function, it's inheriting the async nature (seems normal).

The main problem comes with external calls, like includes, or new statements (because of autoload resolution), and external functions / dynamic calls.

The async nature of a function can't be resolved statically, so if I handle async, everything goes async, so loosing performance.

I need a way to handle async code statically in order to avoid extra async "polution" over all functions...