Search code examples
javascriptc++v8

Has the V8 engine used C++ to replace parts of the codebase previously written in JavaScript?


I have read the V8 engine source code before. And I can find the JavaScript-implemented code in it, e.g. Array.js.

Recently, I want to find the source code for array sorting again, and found that the JS part has been removed. All I can find is array-sort.tq, which is in [v8/third_party/v8/builtins].

Is there a problem with the method I am looking for? Or is it that just the JS part has been removed? It's hard for a JavaScript developer to know the details of the implementation.


Solution

  • Some builtins (such as Array.prototype.sort) are now written in Torque rather than C++ or JavaScript. Torque is a language built for V8:

    The language was designed to be simple enough to make it easy to directly translate the ECMAScript specification into an implementation in V8, but powerful enough to express the low-level V8 optimization tricks in a robust way, like creating fast-paths based on tests for specific object-shapes.

    ...

    Torque provides language constructs to represent high-level, semantically-rich tidbits of V8 implementation, and the Torque compiler converts these morsels into efficient assembly code using the CodeStubAssembler.

    (More about CodeStubAssembler here.)

    More in the Torque builtins blog post.

    So yes, Array.prototype.sort and many other Array methods are written in Torque now, which is compiled to efficient assembly code, which is used by V8's JavaScript interpreter (Ignition) and JavaScript compiler (TurboFan). (Yes, V8 has both. :-) More here, but briefly: V8 parses JavaScript to bytecode, then interprets it with Ignition. Hotspots [areas that are run a lot] get compiled to native code via TurboFan as and when needed.)