javascript - Why node.js is fast when it's single threaded? -
despite being single threaded, how node.js faster? haven't run tests find statistics, while digging in node.js forums, find says it's faster , more lightweight. no matter how light weight is, how can single threaded server faster multi thread ones?
first, why program faster when multi-threaded ?
it's partly due fact multi-threaded program can run on multiple cores main reason, far, when thread waiting io operation (which often, in server), other threads can still progress.
now, node ?
node isn't single threaded. user script in js executed in 1 thread io operations natively handled engine , os multi-threaded.
in practice, means several requests handled in parallel. here's (very) simplified example of possible sequence of actions:
user script | node + os "threads" (libuv) ------------------------------------------------------------- receive , analyze request 1 | ask node file 1 | fetching file 1 receive , analyze request 2 | fetching file 1 ask node file 2 | fetching file 1, fetching file 2 prepare response header 1 | fetching file 2 tell node send file 1 | send file 1, fetching file 2 prepare response header 2 | send file 1 tell node send file 2 | send file 1, send file 2
the whole architecture of node (and io.js) makes simple have high level of parallelism. user thread called event loop short tasks stop @ next io operation (well, not io, often) when code gives node callback called when operation finished.
of course works when you're using asynchronous functions of node. time use function ending in "sync" writefilesync, you're defeating parallelism.
Comments
Post a Comment