使用绑定与仅传递'这'

Performance difference between using bind vs. just passing 'this'

本文关键字:绑定      更新时间:2023-09-26

我将运行一些针对之间差异的jsPerf测试

    function Pool(){

    }
    function internal(data){   //private function

    }
    Pool.prototype.run = function(data){   // public function
       return internal.bind(this)(data);
    }
    module.exports = Pool;

与避免绑定调用和只将"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;

//两个.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毫秒的差异,这似乎不太值得关注。

然而,总而言之,在不使用绑定的情况下,我们看到避免绑定会导致代码几乎比4x快,因为3091851/802445 = 3.85

因此,如果没有绑定,您的代码运行~3.85的速度会快3倍,但两者都很快(显然(,所以除非您正在编写一个框架,否则可能没什么大不了的。