Created
November 20, 2018 20:24
-
-
Save mraleph/0032fa188735417f78486181d5df9250 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
function createSlowObject() { | |
let obj = {}; | |
for (let i = 0; i < 100; i++) { | |
obj['f' + i] = i; | |
} | |
return obj; | |
} | |
function benchmark(obj) { | |
let blackhole = 0; | |
let start = performance.now(); | |
let iterations = 0; | |
let took = 0; | |
while ((took = (performance.now() - start)) < 2000) { | |
for (let i = 0; i < 1e6; i++) { | |
blackhole ^= obj.f0; | |
} | |
iterations++; | |
} | |
return `computed ${blackhole} @ ${took / iterations} ms/iteration`; | |
} | |
function areYouFast(obj) { | |
print(`object has ${%HasFastProperties(obj) ? 'fast' : 'slow'} properties`); | |
} | |
function measure(obj, f) { | |
f(obj); | |
print(`${f.displayName || f.name}: ${f(obj)}`); | |
} | |
function clone(f) { | |
let clone = Function(`return ${f.toString()}`)(); | |
clone.displayName = `clone of ${f.displayName || f.name}`; | |
return clone; | |
} | |
let slowObj = createSlowObject(); | |
print('--- Created slowObj with 100 properties'); | |
areYouFast(slowObj); // => slow | |
measure(slowObj, benchmark); // => 8.2 ms/iteration | |
(function () {}).prototype = slowObj; | |
print('--- After (function () { }).prototype = F'); | |
areYouFast(slowObj); // => slow | |
measure(slowObj, benchmark); // => 7.0 ms/iteration | |
areYouFast(slowObj); // => fast | |
measure(slowObj, benchmark); // => 7.0 ms/iteration | |
measure(slowObj, clone(benchmark)); // => 0.5 ms/iteration |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment