javascriptv8

OptimizeFunctionOnNextCall() and PrepareFunctionForOptimization() + OptimizeFunctionOnNextCall()


What is the difference between using '%OptimizeFunctionOnNextCall()' alone and using '%OptimizeFunctionOnNextCall()' accompanied with '%PrepareFunctionForOptimization()'?

function test() {
    // some code here to optimize
}

%OptimizeFunctionOnNextCall(test);
test();

// ./d8 test.js --allow-natives-syntax --trace-turbo --trace-turbo-path turbo_out --trace-turbo-filter test
function test() {
    // some code here to optimize
}

%PrepareFunctionForOptimization(test);
test();
%OptimizeFunctionOnNextCall(test);
test();

// ./d8 test.js --allow-natives-syntax --trace-turbo --trace-turbo-path turbo_out --trace-turbo-filter test

Solution

  • TL;DR: %PrepareFunctionForOptimization ensures that the function is collecting feedback.


    For Turbofan/Maglev compilation to have any benefit, a function needs to have ran a few times and collected type feedback on what its inputs are. This feedback is collected in what is called a "feedback vector". In order to save memory, feedback vectors are lazily allocated only after a function has been executed a few times (where "a few times" is defined by the invocation_count_for_feedback_allocation flag; currently 8).

    %PrepareFunctionForOptimization forces the allocation of the feedback vector of a given function (cf its implementation), thus ensuring that starting from its next call, it will be collecting feedback.

    So, the normal flow to write JavaScript unit tests for V8 is thus typically

    %PrepareFunctionForOptimization(foo); // Allocates feedback vector
    foo(); // Collect feedback
    %OptimizeFunctioOnNextCall(foo); // Trigger optimization on next call, which will
    foo();                           // optimize based on the feedback collected so far. 
    

    Note that using %OptimizeFunctionOnNextCall without having called %PrepareFunctionForOptimization before should crash (unless you use specific flags like --fuzzing), because it's pretty much never what you want: optimizing without feedback is very rarely useful.