我正在编写一个恒定时间的字符串比较函数(用于 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/