Last active
October 24, 2016 20:15
-
-
Save gabejohnson/e236d5b58ca603d8d37fc7a6dc740ab8 to your computer and use it in GitHub Desktop.
Performance of Function.prototype.call
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
function test(f) { | |
var counter = 10000000; | |
performance.clearMarks(); | |
performance.mark('StartTest'); | |
for(var i = counter; i > 0; --i) { | |
f(); | |
} | |
performance.mark('EndTest'); | |
var marks = performance.getEntriesByType('mark'); | |
return marks[1].startTime-marks[0].startTime; | |
} | |
function testFunc() { | |
return this.x * this.x; | |
} | |
function add(a,b) { return a+b; } | |
function sum(ns) { return ns.reduce(add,0); } | |
function avg(ns) { return sum(ns)/ns.length; } | |
function report(run) { console.log(run.description, ':', avg(run), 'ms') } | |
function Foo(x) { this.x = x; } | |
Foo.prototype.test = testFunc; | |
var obj1 = new Foo(10); | |
var obj2 = { x: 10 }; | |
function testRun(f) { | |
var runs = []; | |
for(var i = 0; i < 10; i++) { | |
runs.push(test(f)); | |
} | |
return runs; | |
} | |
testRun(() => obj1.test()); // if i don't do this, the tests are elided or something | |
var runs = [ | |
()=> obj1.test(), | |
()=> obj1.test.call(obj1), | |
()=> testFunc.call(obj1), | |
()=> testFunc.call(obj2), | |
()=> obj1.test.call(obj2), | |
()=> obj1.test.call({x:10}), | |
()=> testFunc.call({x:10}) | |
].map(t => { | |
var run = testRun(t); | |
run.description = t.toString(); | |
return run; | |
}); | |
runs.forEach(report); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment