如何禁用V8的优化编译器

Dav*_*och 7 javascript google-chrome v8 compiler-optimization node.js

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

我知道,使用with{}(或try/catch语句)块将禁用优化编译器现在,但恐怕这个"功能"(错误)将被固定在未来的版本.

是否存在禁用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并且只是为了好玩而进行性能测试.

Esa*_*ija 8

如果你想要坚实的方法,你需要运行带有--allow-natives-syntax标志的节点并调用它:

%NeverOptimizeFunction(constantTimeStringCompare);
Run Code Online (Sandbox Code Playgroud)

请注意,在调用之前应该调用它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;

}
Run Code Online (Sandbox Code Playgroud)

仅提及with语句会破坏整个包含函数 - 优化是在函数级粒度而非每个语句完成的.