Home >Web Front-end >JS Tutorial >Discussion on asynchronous IO performance of Node.js_node.js
Python and Ruby also have such frameworks, but because libraries containing synchronization code are inevitably used in actual use, they have not grown up. Before Node.js, JavaScript server-side programming was almost blank. , so Node.js was able to build a code base where all IO is asynchronous.
The bottleneck of most web applications is IO, that is, reading and writing to disk, reading and writing to network, and reading and writing to database. What strategy to use to wait for this period of time becomes the key point to improve performance.
PHP’s strategy: run multiple processes and directly wait for IO to complete. Disadvantages: Multiple processes consume multiple copies of memory, making it difficult to share data between processes.
The usual C/C strategy: run in multiple threads, and the program maintains the lock status by itself. Disadvantages: high development cost, error-prone, and difficult to debug.
Python (Tornado): Multiple requests are executed in turn in a single process, switching to another request when IO is encountered. Disadvantages: Still not the most efficient use of time for a single request.
What is "the most efficient use of time"? For example, there are two unrelated database queries. In PHP, one is usually executed first, and then the second one is executed after the execution is completed (the total time is a b). Obviously this is not the most efficient, and both queries should be executed at the same time. is max(a, b).
The problem with Python and other languages that support multi-threading is that at the language level, it is difficult for programmers to tell the virtual machine that two operations should be performed at the same time. Even if there is a way, it is quite troublesome, and most people are too lazy to use it. (Not worth using either). And because Node.js frantically forces all IO to be executed asynchronously, Node.js programmers can also be said to be familiar with it. With some libraries that improve code readability (promise, async), they can easily make unrelated operations execute in parallel. .
The implementation of asynchronous IO has been discussed above, so what are the advantages of asynchronous IO? In fact, asynchronous IO cannot magically reduce the pressure on the server. If you need to add a server, you still need to add a server. However, asynchronous IO will reduce the time of a single request and eliminate the meaningless waiting time in a single request. Therefore, the number of requests processed per unit time has not changed, but the processing time of each request has decreased. From this perspective, the server also saves some resources - that is, the memory consumed by maintaining the connection for each request.