[英]Trying to understand the difference between passing 'this' vs. a reference to the event
[英]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.