search
HomeWeb Front-endJS TutorialWhat is EventLoop? How to test the performance of Node or page

Everyone should know about the Event Loop mechanism. This article uses EventLoop to make an interesting code for detecting node or page performance. By the way, I introduce EventLoop. I hope it will be helpful to everyone!

What is EventLoop? How to test the performance of Node or page

Event Loop

Everyone should know the mechanism of Event Loop. Let me repeat the summary first.

The Event Loop of Node.js is different from that of Javascript. Intuitively, there are two more APIs, setImmediate and process.nextTick. Secondly, due to different runtimes, Html Standrad will consider different task queues for different sources such as multiple pages and DOM operations. There are not so many things to consider in Node.js Event Loop.

According to my understanding, the two parties are conceptually consistent and can be summarized as follows (or see here):

  • task queue task queue . Some events are defined as tasks, and are often called MacroTask (macro task) to correspond to MicroTask. Each time, the task at the head of the queue will be obtained for execution.

  • microtask queue Microtask queue. There will be a microtask queue, and the microtask queue will usually be cleared within a Task.

  • And so on.

Performance Measurement

After understanding the above, there is a simple way to measure performance: how many times per second is completed Event Loop loop, or how many MacroTasks are executed, so that we can roughly know the execution of the synchronized code in the code.

After testing the function

class MacroTaskChecker {
    constructor(macroTaskDispatcher, count = 1000, cb = () => { }) {
        this.macroTaskDispatcher = macroTaskDispatcher
        this.COUNT = count
        this.cb = cb
    }
    start(cb) {
        this.cb = cb || this.cb
        this.stop = false
        const scope = () => {
            let count = this.COUNT
            const startTime = performance.now()
            const fn = () => {
                count--
                if (count > 0) this.macroTaskDispatcher(fn)
                else {
                    const endTime = performance.now()
                    // 执行 COUNT 次宏任务之后 计算平均每秒执行了多少个
                    this.cb({
                        avg: this.COUNT / (endTime - startTime) * 1000,
                        timestamp: endTime
                    })
                    !this.stop && this.macroTaskDispatcher(scope)
                }
            }
            this.macroTaskDispatcher(fn)
        }
        scope()
    }

    stop() {
        this.stop = true
    }
}

, execute some infinite loops to test whether intensive synchronous code execution can be detected.

function meaninglessRun(time) {
    console.time('meaninglessRun')
    for (let i = time; i--; i > 0) {
        // do nothing
    }
    console.timeEnd('meaninglessRun')
}

setTimeout(() => {
    meaninglessRun(1000 * 1000 * 1000)
}, 1000 * 5)

setTimeout(() => {
    checker.stop()
    console.log('stop')
}, 1000 * 20)

<span style="font-size: 18px;">setTimeout</span>

const checker = new MacroTaskChecker(setTimeout, 100)

checker.start(v => console.log(`time: ${v.timestamp.toFixed(2)} avg: ${v.avg.toFixed(2)}`))

It can be clearly seen from the output that avg decreases when synchronization is blocked. However, there will be obvious differences between the two tests on browser and node.js. [Related tutorial recommendations: nodejs video tutorial]

// node.js
time: 4837.47 avg: 825.14
time: 4958.18 avg: 829.83
meaninglessRun: 918.626ms
time: 6001.69 avg: 95.95
time: 6125.72 avg: 817.18
time: 6285.07 avg: 635.16
// browser
time: 153529.90 avg: 205.21
time: 154023.40 avg: 204.46
meaninglessRun: 924.463ms
time: 155424.00 avg: 71.62
time: 155908.80 avg: 208.29
time: 156383.70 avg: 213.04

Although we have achieved our goal, using setTimeout is not completely able to accurately record every task. According to HTML Standrad and MDN, setTimeout will wait at least 4ms. Viewed from this angle browser avg * 4ms \approx 1000ms. Node.js probably doesn't follow the browser's convention, but it doesn't record every loop either.

<span style="font-size: 18px;">setImmediate</span>

If you use node.js’ setImmediate:

const checker = new MacroTaskChecker(setImmediate, 1000 * 10)

You can see that the number of executions is about one order of magnitude higher than Node.js setTimeout:

time: 4839.71 avg: 59271.54
time: 5032.99 avg: 51778.84
meaninglessRun: 922.182ms
time: 6122.44 avg: 9179.95
time: 6338.32 avg: 46351.38
time: 6536.66 avg: 50459.77

According to the explanation in the Node.js document, setImmediate Will be executed in the check phase of each loop (phase). Using setImmediate should be able to accurately record every Loop. The number of cycles of my machine is probably between 40,000 and 60,000.

<span style="font-size: 18px;">window.postMessage</span>

Since there is no setImmediate on the browser, we can follow MDN The instructions use window.postMessage to implement one.

如果想在浏览器中实现 0ms 延时的定时器,你可以参考这里所说的 window.postMessage()

const fns = []
window.addEventListener("message", () => {
    const currentFns = [...fns]
    fns.length = 0
    currentFns.forEach(fn => fn())
}, true);
function messageChannelMacroTaskDispatcher(fn) {
    fns.push(fn)
    window.postMessage(1)
}

可以看到和 node.js setImmediate 量级是一致的。

time: 78769.70 avg: 51759.83
time: 78975.60 avg: 48614.49
meaninglessRun: 921.143 ms
time: 80111.50 avg: 8805.14
time: 80327.00 avg: 46425.26
time: 80539.10 avg: 47169.81

<span style="font-size: 18px;">MessageChannel</span>

browser

理论上 browser 使用 MessageChannel 应该也是可以的,还避免了无效的消息被其他 window.addEventListener("message", handler) 接收:

const { port1, port2 } = new MessageChannel();
const fns = []
port1.onmessage = () => {
    const currentFns = [...fns]
    fns.length = 0
    currentFns.forEach(fn => fn())
};
function messageChannelMacroTaskDispatcher(fn) {
    fns.push(fn)
    port2.postMessage(1)
}

不是很懂为啥会比 window.postMessage 频繁一点,同时启动两个 checker 的话可以看到 log 是成对出现的,也就是说一个loop内大家都只执行了一次。我猜测是 window.postMessage 的实现方式消耗会大一些。

time: 54974.80 avg: 68823.12
time: 55121.00 avg: 68493.15
meaninglessRun: 925.160888671875 ms
time: 56204.60 avg: 9229.35
time: 56353.00 avg: 67430.88
time: 56503.10 avg: 66666.67
// 一起执行 wp=window.postMessage mc=MessageChannel
wp time: 43307.90 avg: 25169.90
mc time: 43678.40 avg: 27005.13
wp time: 43678.60 avg: 26990.55
mc time: 44065.80 avg: 25833.12
wp time: 44066.00 avg: 25819.78
mc time: 44458.40 avg: 25484.20

node

在 node.js 上也有 MessageChannel ,是否也可以用来测量loop次数呢?

mc time: 460.99 avg: 353930.80
mc time: 489.52 avg: 355088.11
mc time: 520.30 avg: 326384.64
mc time: 551.78 avg: 320427.29

量级很不正常。理论上不应该超过 setImmediate 的。如果同时启动 setImmediatesetTimeout 的 checker:

...
(messagechannel) time: 1231.10 avg: 355569.31
(messagechannel) time: 1260.14 avg: 345825.77
(setImmediate) time: 1269.95 avg: 339.27
(setTimeout) time: 1270.09 avg: 339.13
(messagechannel) time: 1293.80 avg: 298141.74
(messagechannel) time: 1322.50 avg: 349939.04
...

很明显跟不是宏任务了。我猜测 MessageChannel 在 node.js 被归入到跟 socket 等同级别了,就是超出阈值之后的任务会移动到下一个loop中。

总结

使用这种方式去检测性能还挺有趣的,正式使用的话这个指标感觉过于不稳定(即使什么都没做都会有20%-30%的振动)。推荐和其他正经的办法(比如 performance 等)结合。

同时这种方式非常有可能影响正常的 Event Loop,比如 Node.js 中会有一个 pull 的阶段,在执行完全部微任务后,没有任何 timer 的话是会停留在这个阶段,准备马上执行下一个出现的微任务。

顺便复习了下 Event Loop。没想到的是 MessageChannel 在两边的差距居然有这么大。

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of What is EventLoop? How to test the performance of Node or page. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

一文解析package.json和package-lock.json一文解析package.json和package-lock.jsonSep 01, 2022 pm 08:02 PM

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

分享一个Nodejs web框架:Fastify分享一个Nodejs web框架:FastifyAug 04, 2022 pm 09:23 PM

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

怎么使用pkg将Node.js项目打包为可执行文件?怎么使用pkg将Node.js项目打包为可执行文件?Jul 26, 2022 pm 07:33 PM

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

手把手带你使用Node.js和adb开发一个手机备份小工具手把手带你使用Node.js和adb开发一个手机备份小工具Apr 14, 2022 pm 09:06 PM

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

图文详解node.js如何构建web服务器图文详解node.js如何构建web服务器Aug 08, 2022 am 10:27 AM

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft