简体   繁体   中英

Why is async code considered so much faster than synchronous?

Why is synchronous code considered so much slower and more resource intensive than asynchronous code? For example nginx is considered faster than Apache and a NodeJS application is considered faster than a PHP application.

Shouldn't it be trivial to compile synchronous code into an asynchronous equivalent? At least in JavaScript many people use libraries like async which help to write synchronous looking code.

Edit : Because of a question in the comments: Synchronous code like

byte[] buf = read(socket);
do_something(buf);

is considered slow because the thread has to block for reading from socket , whereas

read(socket, function(buf) {
    do_something(buf);
});

is considered fast. On the one hand the transformation should be trivial on the other hand both code has to wait for read just one time the thread has to be yielded whereas in the other case a return to the main event loop is necessary

Asynchronous/non-blocking designs are not necessarily faster, but they can scale better than synchronous/blocking designs under some circumstances. Thus, they can be "faster" when handling high volumes of parallel transactions.

There are two primary reasons for the performance differences between the two approaches. One reason is the overhead of thread context switching, the other is the memory consumption of threads on some platforms (eg Java)

I recently completed an article that explains why asynchronous can scale better. I hope it is helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM