6

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:

  1. Is using chained promises really faster nowadays, or is my benchmark misleading?
  2. 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?
7
  • 1
    I don't know Raku, but in Javascript, (micro)benchmarks that use only (the equivalent to) Promise.kept rarely produce insights that are transferable to actually asynchronous code. Commented Mar 11 at 11:05
  • 1
    I have my doubts too, which is why I asked my first question :) Commented Mar 11 at 12:30
  • 1
    4.884666701 seconds using 'start' 5.215426707 seconds using 'then' Commented Mar 14 at 17:34
  • Interesting... Thanks. So, it depends heavily on the equipment. Commented Mar 15 at 18:20
  • "So, it depends heavily on the equipment." That's a fundamentally incorrect conclusion. See google.com/search?q=problems+with+benchmarking+code Commented Mar 19 at 16:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.