Home > Back-end >  Difference between native async functions and wrapping sync functions in a "sync-to-async"
Difference between native async functions and wrapping sync functions in a "sync-to-async"

Time:04-22

As an example for my question, I am building an application that uses the web3.py library. This library only works synchronously, but I require my application to be asynchronous.

The web3.py devs are actually working on building async functionality into the library, but it is taking some time. In the meantime, what I have done is used asyncer.asyncify() to wrap any of the web3.py sync functions I need, to make them work asynchronously in my application, and thus, I believe, I have web3.py working fully asynchronously.

This has got me thinking - what is the difference in a library's authors writing native async functions, rather than just wrapping all of their existing sync functions in something like Asyncer? Would there be any performance differences?

In other words, why do they bother spending so much time translating their sync implementation of their library into async, when they could just use a wrapper function/decorator like Asyncer and have their entire library translated to an async implementation in probably 1 day's work?

CodePudding user response:

I would say ideally asynchronous code should only use asynchronous means for IO-bound tasks. In this case, everything will work in one thread.

In the example with the asyncer that you provided, executing by means of thread pool is used under the hood. This imposes certain costs on starting, switching threads and passing parameters (queue is used).

As a temporary or compromise solution, this may be suitable. But if we want to get more performance for an IO-bound solution, it's better to use asynchronous tools.

  • Related