Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm writing a constant-time string comparison function (for node.js) and would like to disable V8's optimizing compiler for this single function; using command-line flags are out of the question.

I know that using a with{} (or try/catch) block will disable the optimizing compiler now, but I'm afraid this "feature" (bug) will be fixed in future versions.

Is there an immutable (and documented) way disabling V8's optimizing compiler?


Example function:

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;
    }
}

And a perf test just for fun.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
274 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want solid way to do it, you need to run node with --allow-natives-syntax flag and call this:

%NeverOptimizeFunction(constantTimeStringCompare);

Note that you should call this before you have called constantTimeStringCompare, if the function is already optimized then this violates an assertion.

Otherwise with statement is your best bet as making it optimizable would be absolute lunacy whereas supporting try/catch would be reasonable. You don't need it to affect your code though, this will be sufficient:

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;

}

Merely mentioning with statement corrupts the entire containing function - the optimizations are done at function-level granularity, not per statement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...