网络科技

    今日:73| 主题:301175
收藏本版
互联网、科技极客的综合动态。

[其他] uws: The importance of JavaScript scope control

[复制链接]
ぁ詠遠∝僾妳 发表于 2016-11-28 07:07:12
129 1
With JavaScript in the picture, you always need to be careful with how you express yourself. Since everything is dynamic and implicit rather than static and explicit, you often find yourself writing far less efficient code than what could be done. Things that seem identical often have major scalability differences when run at scale.
  Memory usage

  So far we have been able to get 1 million WebSockets in Node.js using 1.2 GB of user space memory. In comparison, this is ~12x more scalable than    ws, the best WebSocket alternative out there for Node.js. However, I recently realized that we can actually reach 1 million connections using only 781 MB from Node.js - a whopping ~20x advantage over    ws.  
  I've done some minor changes to the JavaScript code, but the most important factor is how the user code looks like. Since µWS is majorly bottlenecked by JavaScript, even the smallest change to your JavaScript code will result in a great deal of improvement:
  1. wss.on('connection', (ws) => {
  2.     ws.on('message', (message) => {
  3.         ws.send(message);
  4.     });
  5. });
复制代码
The above code is terrible for scalability since it defines the (anonymous) function inside of the connection handler. As any JavaScripter should know, this will propagate the scope of the current context into the newly defined function. When we then attach this function to the (persistent) WebSocket, we also attach the scope, which thus also becomes persistent.
  Going from ~12x to ~20x scalability advantage only requires the user to swap their code with this or similar:
  1. function onMessage(message) {
  2.     ws.send(message);
  3. }
  4. wss.on('connection', (ws) => {
  5.     ws.on('message', onMessage);
  6. });
复制代码
I tested this change using    wsto see how much of an improvement it made there, but since    wshas far deeper scalability problems this change didn't improve anything significantly or even remotely measurable.
怜容 发表于 2016-11-28 09:01:58
看完帖子,洗洗睡了!
回复 支持 反对

使用道具 举报

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表