Created
January 17, 2023 14:30
-
-
Save AriPerkkio/7495429a0665fd6ebd3e384820123749 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
/* | |
rm -rf ./profiling | |
node --cpu-prof --cpu-prof-dir=./profiling index.mjs | |
*/ | |
import { fileURLToPath } from "node:url"; | |
import vm from "node:vm"; | |
import { Worker, isMainThread } from "node:worker_threads"; | |
globalThis.variableInGlobalScope = "Hello world"; | |
const code = ` | |
function functionRunningInVm() { | |
let sum = 0; | |
for (const [i] of Array(50_000_000).fill(null).entries()) { | |
sum += i; | |
} | |
console.log("sum in vm is", sum); | |
return \`globalThis.variableInGlobalScope in vm is \${globalThis.variableInGlobalScope}\`; | |
} | |
console.log('Running functionRunningInVm'); | |
functionRunningInVm(); | |
`; | |
function functionRunningInMainThread() { | |
let sum = 0; | |
for (const [i] of Array(50_000_000).fill(null).entries()) { | |
sum += i; | |
} | |
console.log("sum is", sum); | |
return sum; | |
} | |
function functionRunningInWorkerThread() { | |
let sum = 0; | |
for (const [i] of Array(50_000_000).fill(null).entries()) { | |
sum += i; | |
} | |
console.log("sum is", sum); | |
return sum; | |
} | |
if (isMainThread) { | |
const worker = new Worker(fileURLToPath(import.meta.url)); | |
worker.on("message", console.log); | |
worker.on("error", console.error); | |
worker.on("exit", console.log); | |
functionRunningInMainThread(); | |
} else { | |
const output = vm.runInThisContext(code); | |
console.log("output is", output); | |
functionRunningInWorkerThread(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment