Why Nodejs serves a file with 80x more CPU usage than Nginx?

Take the same code that sits on nodejs.org home page. Serve a static file that is 1.8Mb. And do the same with Nginx, and watch the difference.

Code :
http://pastie.org/3730760

Screencast :
http://screencast.com/t/Or44Xie11Fnp

Please share if you know anything that’d prevent this from happening, so we don’t need to deploy nginx servers and complicate our lives.

ps1. this test is done with node 0.6.12. out of curiosity, i downgraded to 0.4.12 just to check if it’s a regression, on the contrary, it was worse. same file used 25% twice.

ps2. this post is not a nodejs hate – we use nodejs, and we love it, except this glitch which actually delayed our launch (made us really sad), and seemed quite serious to me. i’ve never read, heard, seen or expected to come across.

Problem courtesy of: Devrim

Solution

The problem with your node benchmark is that you store the static file in a variable inside the V8 heap. Due to the way how V8 handles memory it can’t directly send data contained in javascript variables to the network, because addresses of allocated objects may change during runtime, therefore V8 has to make a copy of your 1.8MB string on every request, sure that kills performance.

What you could do is to use a Buffer
:

replace: longAssString = fs.readFileSync(pathToABigFile, 'utf8');

with: longAssString = fs.readFileSync(pathToABigFile);

that way you have your static file in a buffer, buffers are stored outside of V8s heap and require no copy when sent to the network and should therefore be much faster.

Solution courtesy of: stewe

Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Why Nodejs serves a file with 80x more CPU usage than Nginx?

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录