pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

非常快的無限循環,不會阻塞 I/O

Very fast endless loop without blocking I/O(非常快的無限循環,不會阻塞 I/O)
本文介紹了非常快的無限循環,不會阻塞 I/O的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

對于不阻塞 I/O 的無限循環,是否有比 window.requestAnimationFrame() 更快的替代方法?

Is there a faster alternative to window.requestAnimationFrame() for endless loops that don't block I/O?

我在循環中所做的與動畫無關,所以我不在乎下一幀何時準備好,并且我讀過 window.requestAnimationFrame() 的上限為顯示器的刷新率或至少等到可以繪制幀.

What I'm doing in the loop isn't related to animation so I don't care when the next frame is ready, and I have read that window.requestAnimationFrame() is capped by the monitor's refresh rate or at least waits until a frame can be drawn.

我也嘗試了以下方法:

function myLoop() {
    // stuff in loop
    setTimeout(myLoop, 4);
}

(4 是因為這是 setTimeout 中的最小間隔,較小的值仍將默認為 4.)但是,我需要比這更好的分辨率.

(The 4 is because that is the minimum interval in setTimeout and smaller values will still default to 4.) However, I need better resolution than this.

還有什么性能更好的嗎?

Is there anything with even better performance out there?

我基本上需要 while(true) 的非阻塞版本.

I basically need a non-blocking version of while(true).

推薦答案

兩個比那個setTimeout運行得更快的東西:

Two things that will run sooner than that setTimeout:

  • process.nextTick 回調(NodeJS 特定):

  • process.nextTick callbacks (NodeJS-specific):

process.nextTick() 方法將回調添加到下一個滴答隊列".一旦事件循環的當前輪次運行完成,當前在下一個滴答隊列中的所有回調都會被調用.

The process.nextTick() method adds the callback to the "next tick queue". Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called.

這不是 setTimeout(fn, 0) 的簡單別名.它效率更高.它在事件循環的后續滴答中觸發任何其他 I/O 事件(包括計時器)之前運行.

This is not a simple alias to setTimeout(fn, 0). It is much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop.

  • 承諾結算通知

  • Promise settlement notifications

    因此,這些可能是您工具帶的工具,可以將其中一個或兩個與 setTimeout 混合使用以達到您想要的平衡.

    So those might be a tools for your toolbelt, doing a mix of one or both of those with setTimeout to achieve the balance you want.

    詳情:

    您可能知道,給定的 JavaScript 線程基于任務隊列(規范稱其為作業隊列)運行;您可能知道,瀏覽器中有一個主要的默認 UI 線程,而 NodeJS 運行一個線程.

    As you probably know, a given JavaScript thread runs on the basis of a task queue (the spec calls it a job queue); and as you probably know, there's one main default UI thread in browsers and NodeJS runs a single thread.

    但事實上,現代實現中至少有兩個任務隊列:我們都認為的主要任務隊列(setTimeout 和事件處理程序放置任務的地方),以及微任務"隊列,在主任務(或宏任務")的處理過程中放置??了某些異步操作.一旦宏任務完成,那些微任務就會被處理,主隊列中的下一個宏任務之前 —即使下一個宏任務在微任務之前排隊.

    But in fact, there are at least two task queues in modern implementations: The main one we all think of (where setTimeout and event handlers put their tasks), and the "microtask" queue where certain async operations are placed during the processing of a main task (or "macrotask"). Those microtasks are processed as soon as the macrotask completes, before the next macrotask in the main queue — even if that next macrotask was queued before the microtasks were.

    nextTick 回調和承諾結算通知都是微任務.因此,調度任一調度異步回調,但將在下一個主要任務之前發生.

    nextTick callbacks and promise settlement notifications are both microtasks. So scheduling either schedules an async callback, but one which will happen before the next main task.

    我們可以在帶有 setInterval 和 promise 解析鏈的瀏覽器中看到:

    We can see that in the browser with setInterval and a promise resolution chain:

    let counter = 0;
    
    // setInterval schedules macrotasks
    let timer = setInterval(() => {
      $("#ticker").text(++counter);
    }, 100);
    
    // Interrupt it
    $("#hog").on("click", function() {
      let x = 300000;
    
      // Queue a single microtask at the start
      Promise.resolve().then(() => console.log(Date.now(), "Begin"));
    
      // `next` schedules a 300k microtasks (promise settlement
      // notifications), which jump ahead of the next task in the main
      // task queue; then we add one at the end to say we're done
      next().then(() => console.log(Date.now(), "End"));
    
      function next() {
        if (--x > 0) {
          if (x === 150000) {
            // In the middle; queue one in the middle
            Promise.resolve().then(function() {
              console.log(Date.now(), "Middle");
            });
          }
          return Promise.resolve().then(next);
        } else {
          return 0;
        }
      }
    });
    
    $("#stop").on("click", function() {
      clearInterval(timer);
    });

    <div id="ticker">&nbsp;</div>
    <div><input id="stop" type="button" value="Stop"></div>
    <div><input id="hog" type="button" value="Hog"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    當您運行它并單擊 Hog 按鈕時,請注意計數器顯示是如何凍結的,然后又會繼續顯示.這是因為提前安排了 300,000 個微任務.還要注意我們編寫的三個日志消息的時間戳(它們不會出現在代碼段控制臺中,直到宏任務顯示它們,但時間戳會顯示它們何時被記錄).

    When you run that and click the Hog button, note how the counter display freezes, then keeps going again. That's because of the 300,000 microtasks that get scheduled ahead of it. Also note the timestamps on the three log messages we write (they don't appear in the snippet console until a macrotask displays them, but the timestamps show us when they were logged).

    所以基本上,您可以安排一堆微任務,并定期讓這些微任務用完并運行下一個宏任務.

    So basically, you could schedule a bunch of microtasks, and periodically let those run out and run the next macrotask.

    注意:我在片段中的瀏覽器示例中使用了 setInterval,但具體而言,setInterval 可能不是一個好的選擇對于使用 NodeJS 進行的類似實驗,因為 NodeJS 的 setInterval 與瀏覽器中的有點不同,并且具有一些令人驚訝的時序特征.

    Note: I've used setInterval for the browser example in the snippet, but setInterval, specifically, may not be a good choice for a similar experiment using NodeJS, as NodeJS's setInterval is a bit different from the one in browsers and has some surprising timing characteristics.

    這篇關于非常快的無限循環,不會阻塞 I/O的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

    【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!
  • 相關文檔推薦

    How to fix BrowserWindow is not a constructor error when creating child window in Electron renderer process(在 Electron 渲染器進程中創建子窗口時如何修復 BrowserWindow 不是構造函數錯誤) - IT屋-程序員軟件開發技術
    mainWindow.loadURL(quot;https://localhost:3000/quot;) show white screen on Electron app(mainWindow.loadURL(https://localhost:3000/) 在 Electron 應用程序上顯示白屏)
    Electron webContents executeJavaScript : Cannot execute script on second on loadURL(Electron webContents executeJavaScript:無法在第二個 loadURL 上執行腳本)
    how to use electron browser window inside components in angular-cli?(如何在angular-cli的組件內使用電子瀏覽器窗口?)
    ElectronJS - sharing redux store between windows?(ElectronJS - 在 Windows 之間共享 redux 存儲?)
    How to access camera/webcamera inside electron app?(如何在電子應用程序中訪問相機/網絡攝像頭?)
    主站蜘蛛池模板: 电子元器件呆滞料_元器件临期库存清仓尾料_尾料优选现货采购处理交易商城 | 建筑资质代办-建筑资质转让找上海国信启航 | 抖音短视频运营_企业网站建设_网络推广_全网自媒体营销-东莞市凌天信息科技有限公司 | 壹作文_中小学生优秀满分作文大全 | 老房子翻新装修,旧房墙面翻新,房屋防水补漏,厨房卫生间改造,室内装潢装修公司 - 一修房屋快修官网 | 青州搬家公司电话_青州搬家公司哪家好「鸿喜」青州搬家 | 郑州水质检测中心_井水检测_河南废气检测_河南中环嘉创检测 | 河北凯普威医疗器材有限公司,高档轮椅系列,推车系列,座厕椅系列,协步椅系列,拐扙系列,卫浴系列 | Safety light curtain|Belt Sway Switches|Pull Rope Switch|ultrasonic flaw detector-Shandong Zhuoxin Machinery Co., Ltd | 铜镍-康铜-锰铜-电阻合金-NC003 - 杭州兴宇合金有限公司 | UV固化机_UVLED光固化机_UV干燥机生产厂家-上海冠顶公司专业生产UV固化机设备 | 沈阳网站建设_沈阳网站制作_沈阳网页设计-做网站就找示剑新零售 沈阳缠绕膜价格_沈阳拉伸膜厂家_沈阳缠绕膜厂家直销 | 九爱图纸|机械CAD图纸下载交流中心| 培训中心-翰香原香酥板栗饼加盟店总部-正宗板栗酥饼技术 | 精密模具-双色注塑模具加工-深圳铭洋宇通 | 北京征地律师,征地拆迁律师,专业拆迁律师,北京拆迁律师,征地纠纷律师,征地诉讼律师,征地拆迁补偿,拆迁律师 - 北京凯诺律师事务所 | 渣土车电机,太阳能跟踪器电机,蜗轮蜗杆减速电机厂家-淄博传强电机 | 光栅尺_Magnescale探规_磁栅尺_笔式位移传感器_苏州德美达 | 二手注塑机回收_旧注塑机回收_二手注塑机买卖 - 大鑫二手注塑机 二手光谱仪维修-德国OBLF光谱仪|进口斯派克光谱仪-热电ARL光谱仪-意大利GNR光谱仪-永晖检测 | 优考试_免费在线考试系统_培训考试系统_题库系统_组卷答题系统_匡优考试 | 陕西安闸机-伸缩门-车牌识别-广告道闸——捷申达门业科技 | 新车测评网_网罗汽车评测资讯_汽车评测门户报道 | 空冷器|空气冷却器|空水冷却器-无锡赛迪森机械有限公司[官网] | 废气处理_废气处理设备_工业废气处理_江苏龙泰环保设备制造有限公司 | 锂电池砂磨机|石墨烯砂磨机|碳纳米管砂磨机-常州市奥能达机械设备有限公司 | 酒吧霸屏软件_酒吧霸屏系统,酒吧微上墙,夜场霸屏软件,酒吧点歌软件,酒吧互动游戏,酒吧大屏幕软件系统下载 | 杭州代理记账费用-公司注销需要多久-公司变更监事_杭州福道财务管理咨询有限公司 | 除尘器布袋骨架,除尘器滤袋,除尘器骨架,电磁脉冲阀膜片,卸灰阀,螺旋输送机-泊头市天润环保机械设备有限公司 | 深圳网站建设-高端企业网站开发-定制网页设计制作公司 | 上海心叶港澳台联考一对一培训_上海心叶港澳台联考,港澳台联考一对一升学指导 | 新能源汽车教学设备厂家报价[汽车教学设备运营18年]-恒信教具 | 全自动过滤器_反冲洗过滤器_自清洗过滤器_量子除垢环_量子环除垢_量子除垢 - 安士睿(北京)过滤设备有限公司 | 胶原检测试剂盒,弹性蛋白检测试剂盒,类克ELISA试剂盒,阿达木单抗ELISA试剂盒-北京群晓科苑生物技术有限公司 | 高楼航空障碍灯厂家哪家好_航空障碍灯厂家_广州北斗星障碍灯有限公司 | 耐火浇注料-喷涂料-浇注料生产厂家_郑州市元领耐火材料有限公司 耐力板-PC阳光板-PC板-PC耐力板 - 嘉兴赢创实业有限公司 | LED太阳能中国结|发光红灯笼|灯杆造型灯|节日灯|太阳能灯笼|LED路灯杆装饰造型灯-北京中海轩光电 | 济南网站策划设计_自适应网站制作_H5企业网站搭建_济南外贸网站制作公司_锐尚 | 台湾Apex减速机_APEX行星减速机_台湾精锐减速机厂家代理【现货】-杭州摩森机电 | 北京企业宣传片拍摄_公司宣传片制作-广告短视频制作_北京宣传片拍摄公司 | 步进驱动器「一体化」步进电机品牌厂家-一体式步进驱动 | 除甲醛公司-甲醛检测治理-杭州创绿家环保科技有限公司-室内空气净化十大品牌 |