Skip to content

Math within vm context is extremely slow #49283

Closed as not planned
Closed as not planned
@a-parser

Description

@a-parser

Version

14.x,16.x,18.x,20.x

Platform

linux/macos

Subsystem

No response

What steps will reproduce the bug?

Accessing to Math within vm context is about x50-x100 slower vs native execution:

native 0.287
context 18.947
context-builtin-pow 0.292
const vm = require('vm');

function math_benchmark(name, builtinPow = false) {
    const startTime = Date.now();
    for(let i = 1; i <= 100_000_000; i++) {
        let x = builtinPow ? i ** 2 : Math.pow(i, 2);
        if(i % 100_000_000 == 0) {
            x && console.log(name, (Date.now() - startTime) / 1000);
        }
    }
}

math_benchmark('native');

const ctx = {console};
ctx.global = ctx;
vm.createContext(ctx);

vm.runInNewContext(`
    ${math_benchmark.toString()}
    math_benchmark("context")
`, ctx);

vm.runInNewContext(`
    ${math_benchmark.toString()}
    math_benchmark("context-builtin-pow", true)
`, ctx);

How often does it reproduce? Is there a required condition?

always, tested on all node versions from 14 to 20

What is the expected behavior? Why is that the expected behavior?

it's expected to have nearly same performance

What do you see instead?

it's slower x50-x100 times

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    v8 engineIssues and PRs related to the V8 dependency.vmIssues and PRs related to the vm subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions