为什么单线程的node.js速度很快? [英] Why node.js is fast when it's single threaded?

查看:64
本文介绍了为什么单线程的node.js速度很快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管是单线程的,node.js的运行速度如何?我没有运行任何测试来查找统计信息,但是在node.js论坛中进行挖掘时,我发现每个人都说它更快,更轻量.但是,无论重量多么轻,单线程服务器如何比多线程服务器更快?

Despite being single threaded, how is node.js is faster? I haven't run any tests to find statistics, but while digging in the node.js forums, I find everyone says it's faster and more lightweight. But no matter how light weight it is, how can a single threaded server be faster than multi thread ones?

推荐答案

首先,为什么程序在多线程时速度更快?

部分原因是多线程程序可以在多个内核上运行,但到目前为止,主要原因是当线程正在等待某些IO操作时(这在服务器中尤其如此),其他线程仍然可以进行.

It's partly due to the fact a multi-threaded program can run on multiple cores but the main reason, by far, is that when a thread is waiting for some IO operation (which is very often, especially in a server), the other threads can still progress.

现在,节点呢?

节点不是单线程的.JS中的用户脚本是在一个线程中执行的,但是所有IO操作都由libuv和操作系统进行本地处理,而libuv和操作系统是多线程.

Node isn't single threaded. The user script in JS is executed in one thread but all IO operations are natively handled by libuv and the OS which are multi-threaded.

在此处更多说明

实际上,这意味着并行处理多个请求.这是一个可能的动作序列的非常非常简化的示例:

In practice, this means that several requests are handled in parallel. Here's a very (very) simplified example of a possible sequence of actions:

user script                     | node + OS "threads" (libuv)
-------------------------------------------------------------
receive and analyze request 1   |
ask node for file 1             | fetching file 1
receive and analyze request 2   | fetching file 1
ask node for file 2             | fetching file 1, fetching file 2
prepare response header 1       | fetching file 2
tell node to send file 1        | send file 1, fetching file 2
prepare response header 2       | send file 1
tell node to send file 2        | send file 1, send file 2

节点(和io.js)的整个体系结构使具有高水平的并行性变得简单.用户线程仅由事件循环调用,用于非常短的任务,这些任务在代码向节点提供回调时(在操作完成时将被调用)而在下一个IO操作(实际上不仅是IO,而且通常是在IO)处停止.

The whole architecture of node (and io.js) makes it simple to have a high level of parallelism. The user thread is only called by the event loop for very short tasks which stop at the next IO operation (well, not really only IO, but most often) when your code gives to node a callback that will be called when the operation finished.

当然,这仅在使用Node的异步功能时有效.每当您使用以"Sync"结尾的函数(例如 writeFileSync )时,您都在击败并发.

Of course this only works when you're using the asynchronous functions of Node. Any time you use a function ending in "Sync" like writeFileSync, you're defeating the concurrency.

这篇关于为什么单线程的node.js速度很快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆