我正在编写一个常量字符串比较函数(用于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;
}
}
性能测试只是为了好玩。
如果您想要可靠的方法,则需要运行带有--allow-natives-syntax
flag的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
语句会破坏整个包含的函数-优化是在函数级粒度上完成的,而不是针对每个语句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句