3 ways to optimize Node.js code that you don't know_node.js
Node.js programs may run very slowly due to limitations in CPU or input and output operations. From a CPU perspective, one of the typical reasons why a program runs slowly is an unoptimized "hot path" (a piece of code that is frequently accessed). From the perspective of input and output, the limitation of program running speed may be affected by the underlying operating system, or it may be due to the failure of Node itself. Or, a slow program may have nothing to do with Node itself. The problem lies in external resources, such as database queries or API calls that are slow and not optimized.
In this article, we will focus on identifying and optimizing operations in the code base that cause CPU heavy operation. At the same time, configuration files for production applications will be explored, and changes that can improve operational efficiency will be analyzed and made.
Due to the single-threaded nature of Node, it is especially important for servers to avoid heavy CPU load. Because the time spent on the CPU takes up time to respond to other requests. If you notice that your application is slow to respond and the CPU is consistently high during this process, analyzing your application can help identify bottlenecks and get your application back to running fast.
Analysis Applications
Replicating slow programs in production is difficult and time-consuming. Thankfully, you don't need to do this yourself. You can collect profile data on your production server and analyze it offline. Let's take a look at several analysis methods.
1. Use kernel-level tools
First, you can use kernel-level tools such as DTrace (Solaris, BSD), perf (Linux), or XPerf (Windows) to collect stack traces from a running process and then generate a flame graph. Kernel-level analysis has minimal impact on running processes. The flame graph is a vector graphic generated based on the call stack that supports zooming in and out. Yunong Xiao from Netflix has given great speeches and tweets about perf in Linux systems to help you deepen your understanding of this technology. If you want to maintain high throughput in a production application, consider using this method.
2,
2. Use V8 analyzer
Another option is to use the V8 profiler directly. This approach shares the process with the program, so it affects program performance. For this reason, please only run the V8 profiler to capture the relevant output when you encounter such problems. The benefit of this approach is that you can use all of Chrome's analysis tools and their output (including flame graphs) to investigate the program.
Please run the following code to test your program:
npm install v8-profiler --save
After that, add the following code to your program:
const profiler = require('v8-profiler') const fs = require('fs') var profilerRunning = false function toggleProfiling () { if (profilerRunning) { const profile = profiler.stopProfiling() console.log('stopped profiling') profile.export() .pipe(fs.createWriteStream('./myapp-'+Date.now()+'.cpuprofile')) .once('error', profiler.deleteAllProfiles) .once('finish', profiler.deleteAllProfiles) profilerRunning = false return } profiler.startProfiling() profilerRunning = true console.log('started profiling') } process.on('SIGUSR2', toggleProfiling)
As soon as you send the SIGUSR2 signal to this process, it will start analyzing. Analysis can be stopped by sending a SIGUSR2 signal again (code below).
kill -SIGUSR2 [pid]
The analysis results of this process will be written to the file in the current working path (please ensure that the path can be written). Since this is a programmable interface, you can trigger it at will (using web endpoints, IPC, etc.). If you have a hunch about when your program will become slow, you can trigger this interface at any time. Setting up automatic triggers is useful to avoid constant monitoring, but it requires you to have a predictive understanding of when and how long captures should last.
Once the profile data has been collected, load it into Chrome Dev Tools and start analyzing!
3. Use process manager
Although using the V8 analyzer directly is very efficient and customizable, it will get into your code base and add yet another dependency to your project that you may not want. An alternative is to use a process manager, which can wrap your program with various tools when you need to analyze it. An optional tool is the SLC command line tool from StrongLoop.
First, run npm install strongloop –g, then run the following code:
slc start [/path/to/app]
The above code will launch your program in the process manager, and you can extract CPU profiling data on demand. To verify and get the application id, run:
slc ctl
You will get results similar to the following:
Service ID: 1 Service Name: my-sluggish-app Environment variables: Name Value NODE_ENV production Instances: Version Agent version Debugger version Cluster size Driver metadata 5.0.1 2.0.2 1.0.0 1 N/A Processes: ID PID WID Listening Ports Tracking objects? CPU profiling? Tracing? Debugging? 1.1.61022 61022 0 1.1.61023 61023 1 0.0.0.0:3000
The process id of the locating application. In this example, the id is 1.1.61023. Now we can start analysis at any time by running the following code:
slc ctl cpu-start 1.1.61023
当我们觉得已经捕获到了迟滞行为,就可以运行以下代码来停止分析器:
slc ctl cpu-stop 1.1.61023
以下代码将写文件至硬盘:
CPU profile written to `node.1.1.61023.cpuprofile`, load into Chrome Dev Tools
好啦,就是这样。你可以像在 V8 分析器里那样把文件加载到 Chrome 里面进一步分析。
作出正确决定
在本文中,笔者展示了三种在 Node 中捕获生产环境下 CPU 使用量的方式。那么,你应该选用哪一种呢?下面是一些帮助你缩小决策范围的想法:
- 我需要分析很长一段时间:使用内核级工具。
- 我想用 Chrome 开发工具:使用 V8 分析器或者过程管理器。
- 我想捕获应用中的特定行为:使用 V8 分析器。
- 我不想影响到程序性能:使用内核级程序
- 我希望我不用挨个测试文件来获取程序分析信息:使用过程管理器
以上就是本文的全部内容,3种Node.js代码优化方式,希望大家可以熟练掌握。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

As one of the most popular programming languages in the world, Java has become the language of choice for many businesses and developers. However, code refactoring is crucial to maintaining code quality and development efficiency. Java code can become increasingly difficult to maintain over time due to its complexity. This article will discuss how to refactor Java code to improve code quality and maintainability. Understand the principles of refactoring The purpose of Java code refactoring is to improve the structure, readability and maintainability of the code, rather than simply "changing the code". because

How to use Node.js for front-end application development? The following article will introduce you to the method of developing front-end applications in Node, which involves the development of presentation layer applications. The solution I shared today is for simple scenarios, aiming to allow front-end developers to complete some simple server-side development tasks without having to master too much background knowledge and professional knowledge about Node.js, even if they have no coding experience.

Everyone should know 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!
