测试 bluebird,并未比原生 Promise 快
发布于 7 年前 作者 hwen 6511 次浏览 来自 问答

都说 bluebird 比 原生 Promise 快。

但我写代码测试下,发现 bluebird 没有比原生 Promise 快,跟设想有点偏差。。。

当然这个测试没有导出 bluebird 比较慢的结论,但表明了,bluebird 并非在所有情况都优于原生 Promise

至于什么情况用 bluebird 比较合适?有经验的来说说

测试代码

'use strict'
const Bluebird = require('bluebird')
const promises = []
const bluebirds = []

for (let i=0; i< 100000; i++) {
  promises.push(new Promise((resolve) => {
    setTimeout(() => {
      resolve(i)
    }, 1)
  }))

  bluebirds.push(new Bluebird((resolve) => {
    setTimeout(() => {
      resolve(i)
    }, 1)
  }))
}

const start = new Date()

Bluebird.all(bluebirds).then(res => {
  console.log('=====')
  console.log(`bluebird: ${new Date() - start}`)
})

Promise.all(promises).then(res => {
  console.log('=====')
  console.log(`promise: ${new Date() - start}`)
})

测试环境:

os:unbuntu 16 node版本切换工具:n i7,16g内存

结果:

1.png

2.png

3.png

4.png

12 回复

与你的node版本是有决定性关系的

@i5ting 但是狼叔,我在node,4,6,7,8几个版本都测了一遍,发觉都是 bluebird 比较慢。。。我的测试代码写得有问题?

@hwen 我做了一下基准测试,Bluebird 快。

const Benchmark = require('benchmark');
const colors = require('colors');
const suite = new Benchmark.Suite;

const Bluebird = require('bluebird')
const promises = []
const bluebirds = []

for (let i = 0; i < 100000; i++) {
    promises.push(new Promise((resolve) => {
        setTimeout(() => {
            resolve(i)
        }, 1)
    }))

    bluebirds.push(new Bluebird((resolve) => {
        setTimeout(() => {
            resolve(i)
        }, 1)
    }))
}

suite
    .add('Native promise'.green, async function () {
        await Promise.all(promises);
    })
    .add('Bluebirds promise'.green, async function () {
        await Bluebird.all(bluebirds);
    })
    .on('cycle', function (event) {
        console.log(String(event.target));
    })
    .on('complete', function () {
        console.log('Fastest is '.red + this.filter('fastest').map('name'));
    })
    .run({ 'async': true });

测试的结果:

Native promise x 5.41 ops/sec ±14.01% (18 runs sampled)
Bluebirds promise x 463 ops/sec ±2.51% (79 runs sampled)
Fastest is Bluebirds promise

@Lizhooh 不错

来自酷炫的 CNodeMD

所以楼主代码哪有问题?

@hjl4zh 楼主把两个任务,并行运行,这带来的后果是:互相抢夺 CPU 资源。可能是原生的 promise 比较厉害,抢得比较多。

@Lizhooh 3q,理解了。👍

@Lizhooh 的测试是有问题的,Benchmark不能这么用。。。。

依你的代码,实际的情况是: Native promise sample 1: 玩命等待等待等待,直到所有的timeout都resolve,注意这里面同时包括了native和bluebird的timeout,因为你是交替settimeout的 Native promise sample 2~18:实际上测试的是Promise.all([10万个已经resolve的promise]);这段代码的性能 Bluebirds promise sample 1~79:实际上测试的是Bluebirds.all([10万个已经resolve的promise]);这段代码的性能

另外,两种方案差两个数量级怎么看都不正常

Native promise x 5.41 ops/sec ±14.01% (18 runs sampled)
Bluebirds promise x 463 ops/sec ±2.51% (79 runs sampled)
Fastest is Bluebirds promise

ps.我尝试修改了一下原始代码,在经过预热后,bluebird比原生promise要慢大概1%左右,这点差距。。。忽略忽略~~~bluebird太方便了

bluebird 官方有完整benchmark ,为什么要自己YY

回到顶部