I'm looking for the right way to write asynchronous routines. Here's a hypothetical example of some asynchronous javascript function:
async function someFunction() {
const data = await Promise.resolve(42); // await some async job
const secondData = isPrime(data); // do some sync job
await Promise.resolve(); // await another async job
const result = secondData === false ? 'ok' : 'err'; // do another sync job
return result; // return result
}
As far as I understand, in Raku we can make a routine asynchronous by just wrapping it in start { }
, or we can use chained promises. Actually, I wrote a simple benchmark to compare these two approaches:
sub test-start { start {
my $data := await Promise.kept(42);
my $second-data := $data.is-prime;
await Promise.kept;
my $result := $second-data == False ?? 'ok' !! 'err';
$result;
} }
sub test-then {
Promise.kept(42).then({
my $data := $_.result;
my $second-data := $data.is-prime;
Promise.kept.then({
my $result := $second-data == False ?? 'ok' !! 'err';
$result;
}).result;
})
}
race for ^100000 {
die if test-start.result ne 'ok';
}
say "{now - INIT now} seconds using 'start'";
my $now = now;
race for ^100000 {
die if test-then.result ne 'ok';
}
say "{now - $now} seconds using 'then'";
On my machine the result is:
8.638755866 seconds using 'start'
4.660412604 seconds using 'then'
It seems that chained promises are faster, but the code becomes more convoluted. So, there are two questions:
- Is using chained promises really faster nowadays, or is my benchmark misleading?
- Rakudo is constantly evolving and various optimizations are made. Can we expect the first approach to match the speed of the second in the future, or will chained promises always remain faster due to some fundamental reason?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744799911a4594430.html
评论列表(0条)