Node.JS中回调嵌套和async/await执行空函数性能效率对比测试

栏目: IT技术 · 发布时间: 4年前

内容简介:asyn/await关键字可以让原来的回调嵌套和链式写法,改造成同步语法。util.promisify可以很方便地将回调函数Promise化,那么Promise函数的async/await执行和回调函数的嵌套执行或链式执行在性能上有差异吗?下面我们会写一个测试用例,用两种方式执行一个空函数1百万次,比较执行时间。执行测试文件,测试环境是 node v12.15.0。

asyn/await关键字可以让原来的回调嵌套和链式写法,改造成同步语法。util.promisify可以很方便地将回调函数Promise化,那么Promise函数的async/await执行和回调函数的嵌套执行或链式执行在性能上有差异吗?

下面我们会写一个测试用例,用两种方式执行一个空函数1百万次,比较执行时间。

var util = require('util')
var count = 1000000

var testCallback = function() {
 var curr = 0
 var time = Date.now()
 var next = function() {
   if (curr++ < count) {
     console.log('callback done', Date.now() - time)
     return
   }

   //TODO

   next()
 }

 next()
}

var testAsync = async function() {
  var next = function(cb) {
    //TODO

    cb && cb()
  }

  var nextAsync = util.promisify(next)

  var time = Date.now()
  for (var i = 0; i < count; i++) {
    await nextAsync()
  }
  console.log('async done', Date.now() - time)
}

testCallback()
testAsync()

执行测试文件,测试环境是 node v12.15.0。

$ node testPerformance.js
callback done 0
async done 682

可以看到,按顺序执行同一个空函数100万次,用时为0,即在1毫秒内完成。

用async/await方式执行,用时682毫秒。

不过如果只执行一次,对性能的影响微乎其微。不过在高并发场所,回调函数的性能要远优于async/await


以上所述就是小编给大家介绍的《Node.JS中回调嵌套和async/await执行空函数性能效率对比测试》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Chinese Authoritarianism in the Information Age

Chinese Authoritarianism in the Information Age

Routledge / 2018-2-13 / GBP 115.00

This book examines information and public opinion control by the authoritarian state in response to popular access to information and upgraded political communication channels among the citizens in co......一起来看看 《Chinese Authoritarianism in the Information Age》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

SHA 加密
SHA 加密

SHA 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试