Created
March 6, 2018 16:59
-
-
Save jkrems/71df0bce1b95101b1417f909ce473075 to your computer and use it in GitHub Desktop.
JSON.parse w/o blocking main thread
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
'use strict'; | |
const ivm = require('isolated-vm'); | |
function handleParseJob(code) { | |
return new ivm.ExternalCopy(JSON.parse(code), { transferOut: true }); | |
} | |
function transferInExternalCopy(copy) { | |
return copy.copy({ transferIn: true }); | |
} | |
function buildParseFunction(parseRef) { | |
return function parseJSONInBackground(json) { | |
return parseRef.apply(undefined, [json]) | |
.then(transferInExternalCopy); | |
} | |
} | |
async function main() { | |
const isolate = new ivm.Isolate(); | |
const context = await isolate.createContext(); | |
context.globalReference().setSync('ivm', ivm); | |
const script = await isolate.compileScript(`${handleParseJob}`); | |
await script.run(context); | |
const parseRef = await context.globalReference().get(handleParseJob.name); | |
const parse = buildParseFunction(parseRef); | |
console.time('all parse'); | |
await Promise.all([ | |
parse('{}'), | |
parse('{"ok":true}'), | |
]).then(console.log, console.error); | |
console.timeEnd('all parse'); | |
} | |
main() | |
.catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment