noed ---- 效能檢測和優化
一、NodeJS 的幾種效能檢測和優化的方法
(1)、確保 Node.js 是最新的Node版本
官網更新的 Node 版本 相較於上一個版本 無論在效能還是程式碼優化都有一定的提升
(2)、使用fast-json-stringify加速 JSON 序列化
在 JSON 序列化時,我們需要識別大量的欄位型別,比如對於 string 型別,我們就需要在兩邊加上"
,對於陣列型別,我們需要遍歷陣列,把每個物件序列化後,用,
隔開,然後在兩邊加上[
和]
, 諸如此類等等。
但如果已經提前通過 Schema 知道每個欄位的型別,那麼就不需要遍歷、識別字段型別,而可以直接用序列化對應的欄位,這就大大減少了計算開銷,這就是
例項:
const fastJson = require('fast-json-stringify')
const stringify = fastJson({
title: 'Example Schema',
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer' },
books: {
type: 'array',
items: {
type: 'string',
uniqueItems: true
}
}
}
})
console.log(stringify({
name: 'Starkwang',
age: 23,
books: ['C++ Primer', 'test']
}))
(3)、提升 Promise 的效能
promise 是解決前端回撥地獄的目前最好辦法 但是其對效能的消耗也是巨大的
所以對於大量非同步邏輯、輕量計算的中介軟體專案而言,可以在程式碼中把全域性的 Promise 換為 bluebird 的實現:
global.Promise = require('bluebird');
(4)、正確地編寫非同步程式碼
(1)、Promise.all()
的並行能力:
// 消耗效能的
async function getUserInfo(id) {
const profile = await getUserProfile(id);
const repo = await getUserRepo(id)
return { profile, repo }
}
// 優化後的
async function getUserInfo(id) {
const [profile, repo] = await Promise.all([
getUserProfile(id),
getUserRepo(id)
])
return { profile, repo }
}
(2)、Promise.any()
async function getServiceIP(name) {
// 從 DNS 和 ZooKeeper 獲取服務 IP,哪個先成功返回用哪個
// 與 Promise.race 不同的是,這裡只有當兩個呼叫都 reject 時,才會丟擲錯誤
return await Promise.any([
getIPFromDNS(name),
getIPFromZooKeeper(name)
])
}
(5)、優化 V8 GC
V8 的垃圾回收器是 stop-the-world/incremental/concurrent/parallel 兼而有之的,對垃圾回收的不同階段做了不同的優化。它將 JavaScript 物件分為趨向於頻繁誕生於死亡的新生代與常駐記憶體的老生代,使用不同的策略進行回收,來降低垃圾回收的開銷。