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
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor