Home > Web Front-end > JS Tutorial > 3 ways to optimize Node.js code that you don't know_node.js

3 ways to optimize Node.js code that you don't know_node.js

WBOY
Release: 2016-05-16 15:13:47
Original
1495 people have browsed it

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
Copy after login

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)
Copy after login

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]
Copy after login

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]
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

当我们觉得已经捕获到了迟滞行为,就可以运行以下代码来停止分析器:

slc ctl cpu-stop 1.1.61023
Copy after login

以下代码将写文件至硬盘:

CPU profile written to `node.1.1.61023.cpuprofile`, load into Chrome Dev Tools
Copy after login

好啦,就是这样。你可以像在 V8 分析器里那样把文件加载到 Chrome 里面进一步分析。

作出正确决定
在本文中,笔者展示了三种在 Node 中捕获生产环境下 CPU 使用量的方式。那么,你应该选用哪一种呢?下面是一些帮助你缩小决策范围的想法:

  • 我需要分析很长一段时间:使用内核级工具。
  • 我想用 Chrome 开发工具:使用 V8 分析器或者过程管理器。
  • 我想捕获应用中的特定行为:使用 V8 分析器。
  • 我不想影响到程序性能:使用内核级程序
  • 我希望我不用挨个测试文件来获取程序分析信息:使用过程管理器

以上就是本文的全部内容,3种Node.js代码优化方式,希望大家可以熟练掌握。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template