Created
March 24, 2018 01:15
-
-
Save thysultan/c9c5f03d3bb7b1c9abb0658b0bf681e7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const N = 10000; | |
const FOO = 'foo'; | |
function test(fn) { | |
var result; | |
for (var i = 0; i < N; ++i) result = fn(); | |
return result; | |
} | |
test(x => x); | |
function makeNaive(klasses) { | |
const instances = klasses.map(klass => { | |
let temp = new klass | |
temp[FOO] = temp[FOO] | |
return temp | |
}); | |
return function naive() { | |
let result; | |
for (const instance of instances) result = instance[FOO](); | |
return result; | |
} | |
} | |
// function makeNaive(klasses) { | |
// const instances = klasses.map(klass => new klass); | |
// return function naive() { | |
// let result; | |
// for (const instance of instances) result = instance.foo(); | |
// return result; | |
// } | |
// } | |
function makeCall(klasses) { | |
const pairs = klasses.map(klass => { | |
const instance = new klass(); | |
const method = instance.foo; | |
return {instance, method}; | |
}); | |
return function call() { | |
let result; | |
for (const {instance, method} of pairs) { | |
result = method.call(instance); | |
} | |
return result; | |
} | |
} | |
function makeBound(klasses) { | |
const fns = klasses.map(klass => { | |
const instance = new klass(); | |
return instance.foo.bind(instance); | |
}); | |
return function bound() { | |
let result; | |
for (const fn of fns) result = fn(); | |
return result; | |
} | |
} | |
var DEGREES = [100, 300, 500, 700, 900]; | |
for (const degree of DEGREES) { | |
const KLASSES = []; | |
for (let i = 0; i < degree; ++i) { | |
KLASSES.push(eval('(class C' + i + ' { foo() { }})')); | |
} | |
const TESTS = [ makeBound(KLASSES), makeCall(KLASSES), makeNaive(KLASSES) ]; | |
for (var j = 0; j < TESTS.length; ++j) { | |
test(TESTS[j]); | |
} | |
for (var j = 0; j < TESTS.length; ++j) { | |
var startTime = Date.now(); | |
test(TESTS[j]); | |
console.log( | |
degree + '|' + TESTS[j].name + ':', (Date.now() - startTime), 'ms.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using bracket notation[variable] access seems to mitigate the performance cliff, as an aside out of JavaScriptCore SpiderMonkey and V8(through d8), SpiderMonkey seems to handle this perf cliff the best, with V8 very considerably slower than both(without this pattern), but maybe this is just due to the version of d8 i'm using or JSC and SpiderMonkey optimizing out some bit of this benchmarks behavior