Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart - Async vs Sync performance considerations

Working with async/await is quite contagious and i end up having asynchronous methods all over my code. This makes me wonder : Is there any difference between those calls ? What about performance ?

class SomeClass{}

//Sync return
SomeClass syncMethod(){
  return SomeClass();
}

//Immediate async return
Future<SomeClass> asyncMethod() async{
  return SomeClass();
}

//Await an immediate async return
Future<SomeClass> otherAsyncMethod() async{
  SomeClass someClass = await asyncMethod();
  return someClass;
}

Thank you !

like image 701
SkR Avatar asked Aug 14 '26 23:08

SkR


1 Answers

Async operations do have an overhead. They create futures, attach listeners to those futures, schedule microtasks, asynchronous complete the futures, etc. All that inevitably takes extra time and space over just returning a value on the stack, and on top of that, you get more latency too because the asynchronous operations might be interleaved with other operations.

An async function like

Future<int> foo(Future<int> bar()) async {
  print("before");
  var result = await bar();
  print("after");
  return result;
}

is equivalent to a function written as:

Future<int> foo(Future<int> bar()) {
  var $c = Completer<int>();
  print("before");
  bar().then((int result) {
    print("after");
    $c.complete(result);
  }, onError: (e, s) {
    $c.completeError(e, s);
  });
  return $c.future;
}

The compiler tries to make something like that (but probably not as good as a hand-crafted rewrite). All of that extra future-management is necessary overhead for an asynchronous function.

That's also the advantage of asynchronicity: You can do something else while you are waiting for, fx, I/O operations. Even with the overhead, a properly written asynchronous program can still be done sooner than if all I/O operations were blocking. And sometimes it's not.

If your program does I/O, then unless it's a very specialized program, chances are the I/O time is going to dominate everything else

like image 151
lrn Avatar answered Aug 18 '26 06:08

lrn