Does V8 detect int variables and process them more efficiently?

This is more about Node.JS, which uses the V8 engine. This is a JavaScript engine that is also used for Google Chrome.

I heard that V8 is very fast, not only for Node, but also for browsers. However, one thing I notice about JavaScript is that types are not encoded for variables.

To do this in Java, you need the variable type Object for everything. This would be significantly less efficient, for example in a for loop:

 for (var i = 0; i < array.length; i++) {} 

My question is, how does V8 handle variable types? Does this know that this variable i always either int or long ? (I see this as unlikely, i++ has the ability to convert a long to double .)

Or does the V8 handle things so that it doesn't matter? I think some simple examples of what the JIT compiler will create will be helpful. Both Java and JavaScript have JIT compilers for converting code to C.

I am not a C programmer, but I am curious to know how types are handled, and if Java is really more efficient in this area. (yes, I know that I / O will be much more significant for most programs than type handling)

+4
source share
1 answer

In a word: Yes.

V8 compiles the code into intermediate bytecode, then the "hot spots" are analyzed by the Crankshaft compiler, and if it determines that some variables will never be anything other than an integer, double, string, or so it generates machine code with unpacked.

It performs this optimization only on branches that have already been traversed; others are delayed until information about the actual types involved is calculated by the "regular" engine, and then entered into optimized code.

In addition, V8 can translate essentially static prototype hierarchies into "classical" inheritance of objects in C ++ to improve performance on "complex" types.

He can do all this only in code called โ€œoftenโ€; like loops or often called functions.

Associated with the article (part of the series) explains this in much, much more detail and is certainly worth reading.

EDIT: But of course, a statically typed language like Java will optimize as much code as possible at compile time, so it should outperform Javascript in all but toy tests. However, V8 closes the gap between them, and Javascript is much more fun to write than Java or C ++, so initial prototyping or developing programs where the user is the biggest source of latency means that Javascript is often the best choice. , in my opinion.

+3
source

Source: https://habr.com/ru/post/1403704/


All Articles