Async / Await会降低服务器性能 [英] Async/Await degrades server performance
本文介绍了Async / Await会降低服务器性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码编写HTTP服务器来检查使用 async / await
是否会影响性能
I'm using the following code to write a HTTP server to check if using async/await
can impact the performance
const http = require('http')
const server = http.createServer(reqResHandler);
server.listen(3000, err => {
if (err) throw err
console.log('Server listening on: http://localost:3000')
})
无承诺
const reqResHandler = (req, res) => {
req.body = [];
req.on('data', (chunk)=>req.body.push(chunk));
req.on('end', ()=>{
req.body = Buffer.concat(req.body);
res.setHeader("content-length", req.body.length);
res.end(req.body);
});
};
承诺
async function getBody(req){
var end = new Promise(function(resolve, reject) {
req.on('data', (chunk)=>req.body.push(chunk));
req.on('end', ()=>{req.body = Buffer.concat(req.body); resolve(req.body)});
req.on('error', reject); // or something like that
});
await end;
return req.body;
}
const reqResHandler = async (req, res) => {
req.body = [];
var data = await getBody(req);
res.setHeader("content-length", data.length);
res.end(data);
};
当我使用没有承诺的代码时,它每秒产生的吞吐量高达30-31k。但是,如果我使用带有promise的代码,那么它的性能最高可达27-27.5k rps。
When I use the code without promise it gives throughput up to 30-31k requests per second. But if I use code with promise then it gives performance up to 27-27.5k rps max.
我是否正确使用异步等待?
Am I using the async await incorrectly?
推荐答案
你可以像这样执行异步:
You can do the async like this:
async function getBody(req){
return new Promise(function(resolve, reject) {
req.on('data', (chunk)=>req.body.push(chunk));
req.on('end', ()=>{req.body = Buffer.concat(req.body); resolve(req.body)});
req.on('error', reject); // or something like that
});
}
const reqResHandler = async (req, res) => {
req.body = [];
let data = (await getBody(req)).body;
res.setHeader("content-length", data.length);
res.end(data);
};
这篇关于Async / Await会降低服务器性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文