繁体   English   中英

使用绑定与仅传递“ this”之间的性能差异

[英]Performance difference between using bind vs. just passing 'this'

我即将运行一些jsPerf测试,目标是

    function Pool(){


    }

    function internal(data){   //private function


    }

    Pool.prototype.run = function(data){   // public function

       return internal.bind(this)(data);

    }

    module.exports = Pool;

与避免bind调用,而只是将“ this”传递给私有函数相比:

function Pool(){


}

function internal(pool, data){   //private function


}

Pool.prototype.run = function(data){   // public function

   return internal(this, data);

}

module.exports = Pool;

我认为使用后一种模式性能更高,是否有理论上的表现可能会更差? jsPerf测试可以告诉我哪个/什么,但不能告诉我为什么。 另外,如果您知道这两种格式的名称,请告诉我,谢谢。

好吧,jsPerf并没有真正为我做到这一点,并且由于Node.js可以使用更高分辨率的计时功能,所以我认为我会运行自己的测试。

因此,我们有两个文件要测试:

//one.js

function Pool(){

}

function internal(data){
    return this['x'] = data;
}


Pool.prototype.init = function(data){
    return internal.bind(this)(data);
};

module.exports = Pool;

//two.js

function Pool(){


}

function internal(pool,data){
    return pool['x'] = data;
}


Pool.prototype.init = function(data){
    return internal(this,data);
};

module.exports = Pool;

然后我们像这样测试文件one.js:

const Pool = require('./one');


var time = process.hrtime();


for (var i = 0; i < 1000; i++) {

   var x =  new Pool().init(String(i) + 'yeah');

}

var diff = process.hrtime(time);

console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);

我们像这样测试文件two.js:

const Pool = require('./two');


var time = process.hrtime();


for (var i = 0; i < 1000; i++) {

    var x = new Pool().init(String(i) + 'yeah');

}


var diff = process.hrtime(time);

console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);

我从https://nodejs.org/api/process.html#process_process_hrtime提取了基准代码

因此,运行测试一

3091851 nanoseconds

并进行两次测试

802445 nanoseconds

所以直接通过它看起来更快,但是真的能传递多少呢?

区别是

2289406 nanoseconds

因此这仅相差2.28毫秒,这似乎并没有太多值得关注。

但是,总的来说,在不使用bind的情况下,避免绑定会导致代码快将近4x ,因为3091851/802445 = 3.85

因此,如果没有绑定,代码的运行速度将提高~3.85倍,但两者都非常快(显然),因此除非您正在编写框架,否则可能没什么大不了的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM