Created
February 23, 2018 22:58
-
-
Save denar90/56bfef7506b8602e0ff12f0469505129 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<script src="./clooney.min.js"></script> | |
<script> | |
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):e.greenlet=n()}(this,function(){return function(e){var n=new Worker(URL.createObjectURL(new Blob(["onmessage=("+function(e){return function(n){var t=n.data;return Promise.resolve().then(function(){return e.apply(e,t[1])}).then(function(e){postMessage([t[0],null,e])},function(e){postMessage([t[0],""+e])})}}+")("+e+")"]))),t=0,o={};return n.onmessage=function(e){var n=e.data,t=n[0],r=n[1];o[t][r?1:0](r||n[2]),delete o[t]},function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return new Promise(function(r,u){o[++t]=[r,u],n.postMessage([t,e])})}}}); | |
//# sourceMappingURL=greenlet.umd.js.map | |
</script> | |
<title>Title</title> | |
</head> | |
<body> | |
<script> | |
class Actor { | |
parse(data) { | |
return JSON.parse(JSON.stringify(data)); | |
} | |
} | |
const parseWithClooney = async (response) => { | |
const instance = await Clooney.spawn(Actor); | |
await instance.parse(response); | |
}; | |
const parseWithGreenlet = async (response) => { | |
const parse = await greenlet(async data => { | |
JSON.parse(JSON.stringify(data)); | |
}); | |
await parse(response); | |
}; | |
const fetchAndParse = async (name, asyncCb) => { | |
await fetch('https://jsonplaceholder.typicode.com/photos', { method: 'GET', | |
headers: new Headers(), | |
mode: 'cors', | |
cache: 'default' }) | |
.then(resp => resp.json()).then(async response => { | |
performance.mark(`parse-with-${name}-start`); | |
await asyncCb(response); | |
performance.mark(`parse-with-${name}-end`); | |
performance.measure( | |
`parse-with-${name}`, | |
`parse-with-${name}-start`, | |
`parse-with-${name}-end` | |
); | |
const measures = performance.getEntriesByName(`parse-with-${name}`); | |
const measure = measures[0]; | |
console.log(`When parse in ${name}, thread busy for ${measure.duration} milliseconds`); | |
performance.clearMarks(); | |
performance.clearMeasures(); | |
}); | |
}; | |
// | |
(async function() { | |
await fetchAndParse('Clooney', parseWithClooney); | |
await fetchAndParse('greenlet', parseWithGreenlet); | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Might be good to include a test where the actor/greenlet are created separately. Usually calls to an existing Worker are much cheaper than creating a new one.