javascript - 如何禁用 V8 的优化编译器

标签 javascript node.js google-chrome v8 compiler-optimization

我正在编写一个恒定时间的字符串比较函数(用于 node.js),并且想为这个单一函数禁用 V8 的优化编译器;使用命令行标志是不可能的。

我知道使用 with{}(或 try/catch) block 将禁用优化编译器现在,但我担心这个“功能”(bug ) 将在未来的版本中修复。

是否有一种不可变的(并记录在案的)方法来禁用 V8 的优化编译器?


示例函数:

function constantTimeStringCompare( a, b ) {
    // By adding a `with` block here, we disable v8's optimizing compiler.
    // Using Object.create(null) ensures we don't have any object prototype properties getting in our way.our way.
    with ( Object.create( null ) ){
        var valid = true,
            length = Math.max( a.length, b.length );
        while ( length-- ) {
            valid &= a.charCodeAt( length ) === b.charCodeAt( length );
        }
        // returns true if valid == 1, false if valid == 0
        return !!valid;
    }
}

还有一个 perf test只是为了好玩。

最佳答案

如果你想要可靠的方法来做到这一点,你需要运行带有 --allow-natives-syntax 标志的 Node 并调用它:

%NeverOptimizeFunction(constantTimeStringCompare);

请注意,您应该在调用 constantTimeStringCompare 之前调用它,如果该函数已经优化,则这违反了断言。

否则 with 语句是您最好的选择,因为使其可优化绝对是疯狂的,而支持 try/catch 则是合理的。你不需要它来影响你的代码,这就足够了:

function constantTimeStringCompare( a, b ) {
    with({});

    var valid = true,
        length = Math.max( a.length, b.length );
    while ( length-- ) {
        valid &= a.charCodeAt( length ) === b.charCodeAt( length );
    }
    // returns true if valid == 1, false if valid == 0
    return !!valid;

}

仅仅提及 with 语句就会破坏整个包含函数 - 优化是在函数级别的粒度上完成的,而不是每个语句。

关于javascript - 如何禁用 V8 的优化编译器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18476402/

相关文章:

html - Microsoft Edge 在使用 <object> 和 <img> 时忽略 SVG 中的高度

google-chrome - Selenium ChromeDriver - 如何作为守护进程运行和部署?

javascript - JavaScript 中的减法问题

javascript - 在 puppeteer 中“找不到给定 ID 的框架”

javascript - 使时间密集型函数异步

google-chrome - 如何在 Chrome 扩展中进行 A/B 测试

javascript - 删除nodeJS应用程序中的所有组和子项

javascript - 将字符串+Javascript中的多行替换为单行

javascript - 切片多维 JSON 数组中一列的最后 2 个对象

javascript - Node.js 在包含的 js 文件中快速渲染