当前位置: 首页 > 后端技术 > Node.js

Node.js服务性能翻倍的秘诀(一)

时间:2023-04-03 15:19:29 Node.js

前言用过Node.js开发的同学一定对koa有所上手,因为其简洁大方的文风,加上丰富的社区生态,众多现有的Node.js框架都是基于koa进行二次封装的。但是说到性能,就不得不提到一个著名的框架:fastify,它的特点是名副其实的快,官方的Benchmarks甚至比Node.js原生的http.Server还快。性能提升的关键我们先来看看fastify是如何启动一个服务的。#安装fastifynpmi-Sfastify@3.9.1//创建一个服务实例constfastify=require('fastify')()app.get('/',{schema:{response:{//key是响应状态code'200':{type:'object',properties:{hello:{type:'string'}}}}}},async()=>{return{hello:'world'}})//开始service;(async()=>{try{constport=3001//监听端口awaitapp.listen(port)console.info(`serverlisteningon${port}`)}catch(err){console.error(err)process.exit(1)}})()从上面的代码可以看出,fastify为请求的响应体定义了一个schema。除了定义响应体的schema之外,fastify还支持对以下数据定义schema:body:当是POST或PUT方法时,校验请求体;query:验证url的查询参数;params:验证url参数;响应:过滤并生成响应主体的模式。app.post('/user/:id',{schema:{params:{type:'object',properties:{id:{type:'number'}}},response:{//2xx表示200~299这个模式'2xx':{type:'object',properties:{id:{type:'number'},name:{type:'string'}}}}}},async(req)=>{constid=req.params.idconstuserInfo=awaitUser.findById(id)//Content-Type默认为application/jsonreturnuserInfo})fastify提高性能的秘诀在于它返回application/json类型的数据那时,而不是使用原生的JSON.stringify,内部重新实现了一套JSON序列化方法。该模式是将JSON序列化性能提高一倍的关键。如何序列化JSON在探索fastify如何序列化JSON数据之前,我们先来看看JSON.stringify需要经过哪些繁琐的步骤。这里参考了开源JSON-jsstringify方法中实现的DouglasCrockford(JSON格式的创造者)。JSON-js:https://github.com/douglascrockford/JSON-js/blob/master/json2.js//只展示了JSON.stringify的核心代码,其他代码省略if(typeofJSON!=="object"){JSON={};}JSON.stringify=function(value){returnstr("",{"":value})}functionstr(key,holder){varvalue=holder[key];switch(typeofvalue){case"string":returnquote(value);案例“数字”:返回(isFinite(值))?字符串(值):“空”;案例“布尔”:案例“空”:返回字符串(值);case"object":if(!value){返回"null";}部分=[];if(Object.prototype.toString.apply(value)==="[objectArray]"){//处理数组length=value.length;for(i=0;i{//key需要加上双引号code+=`json+='${$String(key)}:'`//通过嵌套const转换值value=properties[key]constresult=nested(laterCode,name,`.${key}`,value)code+=result.codelaterCode=result.laterCodeif(i