700 Software
700 Software

Reputation: 87793

Does V8 detect int variables and handle them more efficiently?

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

I hear about V8 being really fast, not just for Node, but for browsers too. However, one thing I notice about JavaScript, is that types are not coded for variables.

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

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

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

Or does V8 handle things in such a way that it does not matter? I think some simple examples of what the JIT compiler would create would be useful. Both Java and JavaScript do have JIT compilers to convert 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 that area. (yes, I know that I/O is going to be much more significant for most programs than type handling)

Upvotes: 5

Views: 873

Answers (1)

user1207456
user1207456

Reputation:

In a word: Yes.

V8 compiles the code into an intermediary bytecode, then the "hotspots" are analyzed by the "Crankshaft" compiler, and if it determines that certain variables will never be anything other than an integer, a double, a string, or so on, it generates machine code with it "unboxed."

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

On top of this, V8 can translate essentially-static prototype hierarchies into "classic" C++-style object inheritance for performance improvements on "complex" types.

It can only do all of this, however, on code that is called "often"; like loops or frequently called functions.

The linked to article (part of a series), explains this in much, much more detail, and is definitely worth reading.

EDIT: But, of course, a statically-typed language like Java will optimize as much of the code as possible at compile time, so it should outperform Javascript in all but toy benchmarks. However, V8 is closing the gap between the two, and Javascript is a lot more "fun" to write than Java or C++, so initial prototyping or development of programs where the user is the largest source of latency means Javascript is often the better choice, in my opinion.

Upvotes: 3

Related Questions