使用绑定与仅传递'这'
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倍,但两者都很快(显然(,所以除非您正在编写一个框架,否则可能没什么大不了的。
相关文章:
- 在VanillaJS中模拟模型双向数据绑定
- 无法通过数组映射绑定
- 主干-不管怎样,检查事件以前是否绑定过
- 用于搜索的聚合物嵌套绑定
- Angular:更新一次性绑定的数据
- 如何使用ngrepeat和双向绑定获得指令的隔离范围
- react.js中的密钥绑定
- 使用regex的jquery keydown绑定不会验证撇号和句点
- 将事件处理程序绑定到任何可能的事件
- AngularJS指令只识别双向绑定类型
- Telerik rad组合框多列数据绑定
- 对API数据使用声明性绑定
- 如何销毁/删除/取消绑定SnapSVG.js
- 在D3.js中,有没有任何方法可以将x和y方向上的滚动事件绑定到平移svg
- 数据绑定:'系统Char'不包含名为'xxxxx'
- react组件中的绑定方法
- 如何将ngrepeat下的ngmodel绑定到$scope
- WinJS内联绑定语法
- ng绑定和ng href问题.ng href未从控制器加载数据
- 如何在动态创建的节点上绑定函数