-
-
Save Raynos/93d275463a90306b4b0779fed308550c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function MyObject() { | |
this.counter = 0; | |
} | |
MyObject.prototype.doSomeWork = function doSomeWork() { | |
this.counter++; | |
}; | |
MyObject.prototype.allocateClosure = | |
function allocateClosure() { | |
var self = this; | |
return function doWork() { | |
self.doSomeWork(); | |
} | |
}; | |
MyObject.prototype.allocateArrow = | |
function allocateArrow() { | |
return () => { this.doSomeWork() }; | |
}; | |
var ALLOC_COUNTER = 50 * 1000 * 1000; | |
var CALL_COUNTER = 400 * 1000 * 1000; | |
function testAllocateClosure() { | |
console.log('test allocate closure'); | |
var obj = new MyObject(); | |
var resultArr = new Array(10); | |
var start = Date.now(); | |
for (var i = 0; i < ALLOC_COUNTER; i++) { | |
resultArr[i % 10] = obj.allocateClosure(); | |
} | |
var end = Date.now(); | |
console.log('time taken', end - start); | |
} | |
function testAllocateArrow() { | |
console.log('test allocate arrow'); | |
var obj = new MyObject(); | |
var resultArr = new Array(10); | |
var start = Date.now(); | |
for (var i = 0; i < ALLOC_COUNTER; i++) { | |
resultArr[i % 10] = obj.allocateArrow(); | |
} | |
var end = Date.now(); | |
console.log('time taken', end - start); | |
} | |
function testCallArrow() { | |
console.log('test call arrow'); | |
var obj = new MyObject(); | |
var arrow = obj.allocateArrow(); | |
var start = Date.now(); | |
for (var i = 0; i < CALL_COUNTER; i++) { | |
arrow(); | |
} | |
var end = Date.now(); | |
console.log('time taken', end - start); | |
} | |
function testCallClosure() { | |
console.log('test call closure'); | |
var obj = new MyObject(); | |
var closure = obj.allocateClosure(); | |
var start = Date.now(); | |
for (var i = 0; i < CALL_COUNTER; i++) { | |
closure(); | |
} | |
var end = Date.now(); | |
console.log('time taken', end - start); | |
} | |
function main(mode) { | |
if (mode === 'alloc-closure') { | |
testAllocateClosure(); | |
} else if (mode === 'alloc-arrow') { | |
testAllocateArrow(); | |
} else if (mode === 'call-closure') { | |
testCallClosure(); | |
} else if (mode === 'call-arrow') { | |
testCallArrow(); | |
} else { | |
console.log('unsupported mode', mode); | |
} | |
} | |
main(process.argv[2]); |
Author
Raynos
commented
Oct 7, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment